我的“子组件”属性未初始化

问题描述 投票:1回答:1

我有一个管理面板组件,其中的另一个组件(wizard.component.ts)称为。

向导组件的步长为1到3,并且我基于此带有ngIf的step属性加载不同的选项卡。向导组件显示,我可以看到

标记,但是ngIf无法正常工作,因为我假设step属性未初始化。

我尝试将this.step = 1添加到ngOnInit,构造函数和ngOnChanges中,但除非我单击并触发一些更改,否则该变量似乎不会初始化。

admin.component.html

  <div class="main-content">


      <!-- HEADER -->
      <div class="header">
        <div class="header-body ml-4">

          <h6 class="header-pretitle">
            Logged in as admin
          </h6>

          <h1 class="header-title">
            Admin panel
          </h1>

        </div>
      </div>
      <app-wizard></app-wizard>
      <!-- CARDS -->


    </div> <!-- / .main-content -->



wizard.component.html

<div *ngIf="step == 1"></div>
<div *ngIf="step == 2"></div>
<div *ngIf="step == 3"></div>

wizard.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-wizard',
  templateUrl: './wizard.component.html',
  styleUrls: ['../../app.component.css','./wizard.component.css']
})
export class WizardComponent implements OnInit {
  step: number = 1
  constructor() { 
    this.step = 1
  }

  start() {
    this.step = 1
  }

  ngOnInit(): void {
    this.step = 1
    setInterval(() => {
      this.start()
    }, 1000);
  }

  ngOnChanges(){
    this.step = 1

  }

  continue(step) {
    this.step = step + 1
  }
  back(step) {
    this.step = step - 1
  }

}

有什么想法吗?谢谢

angular
1个回答
0
投票

无需担心挂入更改,仅应在设置新的步长值方面更新视图。我假设您只想要一些基本的东西,例如:

export class WizardComponent implements OnInit{
  public step: number;

  public ngOnInit(): void {
    this.step = 1;
  }

  public next(): void {
    this.step = this.step + 1;
  }

  public prev(): void {
    this.step = this.step - 1;
  }
}

模板:

<div class="controls">
  <button [disabled]="step === 1" (click)="prev()">Back</button>
  <button (click)="next()">Next</button>
<div>

<div *ngIf="step === 1"> Tab 1 content </div>
<div *ngIf="step === 2"> Tab 2 content </div>
<div *ngIf="step === 3"> Tab 3 content </div>

编辑:

为此创建了一个基本的StackBlitz:https://stackblitz.com/edit/angular-nashof

© www.soinside.com 2019 - 2024. All rights reserved.