ng如果条件已切换但未显示

时间:2019-10-16 17:45:18

标签: angular

我有三个组成部分

componentOne

  public step = 'two';

  updateStep() {
    this.step = 'three';
    console.log('new step: ' + this.step);
  }

<div *ngIf="step === 'two'">
   <app-step-two></app-step-two>
</div>
<div *ngIf="step === 'three'">
   <app-step-three></app-step-three>
</div>

componentTwo

 constructor(private parent: componentOne) { }
  buttonClicked() {
     this.parent.updateStep();
  }

<div> This is two </div>
<button (click)="buttonClicked()" >test</button>

componentThree

<div> this should be displayed </div>

在ComponentOne中,我看到的视图已初始化为查看步骤2。但是,当调用update()时,视图为何不切换到步骤3?

编辑:我的意思是

<div *ngIf="step === 'three'">
   <app-step-three></app-step-three>
</div>

假设要显示...但是不是

2 个答案:

答案 0 :(得分:1)

componentTwo

import { Output, EventEmitter } from '@angular/core';

@Output('updateStep') updateStep = new EventEmitter();

constructor() { }

buttonClicked() {
    this.updateStep.emit();
}

<div> This is two </div>
<button (click)="buttonClicked()" >test</button>

componentOne

<app-step-two (updateStep)="updateStep()"></app-step-two>

说明

componentOne是componentTwo和componentThree的父组件。

您应该使用Output方法将事件从子组件发送到父组件。

您无需将AppComponent注入FirstComponent!

UPD 参见this sample

答案 1 :(得分:1)

没有clicked事件。有click。参见this sample

@Component({
  selector: 'first',
  template: `<div> This is two </div><button (click)="buttonClicked()" >test</button>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class FirstComponent  {
  constructor(private parent: AppComponent) { }
  buttonClicked() {
     this.parent.updateStep();
  }
}