显示/隐藏子组件

时间:2019-01-11 16:27:24

标签: angular

想象一下下面的HTML代码,它是Angular组件的模板:

<form [formGroup]="myForm">
  <app-one></app-one>
  <app-two [someService]="someService"></app-two>
  <app-three></app-three>
  <button type="button"  (click)="submit()">Submit</button>
  <button type="button"  (click)="next()">Next</button>
</form>

我想要的不是一次显示所有子组件(UI会变得太大),而是一次单击Next按钮一次。首先, 我希望出现<app-one>,然后在Next <app-two>上替换<app-one>,然后在第二Next上单击<app-three>来替换<app-two>Submit按钮来代替Next按钮。 我可以使用*ngIf指令来实现,但是我确信必须有更好的方法(使用ng-templateng-container?)。 有帮助吗?

2 个答案:

答案 0 :(得分:1)

我认为您假装的就像是步进机,link将会为您展示示例。

您还可以创建一个变量来保存用户所在的步骤。 例如:

<form [formGroup]="myForm">
   <app-one *ngIf="step==1"></app-one>
   <app-two *ngIf="step==2" [someService]="someService"></app-two>
   <app-three *ngIf="step==3"></app-three>
   <button type="button"  (click)="submit()">Submit</button>
   <button type="button"  (click)="next()">Next</button>
</form>

答案 1 :(得分:1)

正确。 * ngIf会不必要地增加圈复杂度。使用 * ngSwitchCase

<form [formGroup]="myForm" [ngSwitch]="currentStep">
  <app-one *ngSwitchCase="step-1"></app-one>
  <app-two *ngSwitchCase="step-2" [someService]="someService"></app-two>
  <app-three *ngSwitchCase="step-3"></app-three>
  <button type="button"  (click)="submit()">Submit</button>
  <button type="button"  (click)="next()">Next</button>
</form>

currentStep的值可以从下一个方法更新

public next(): void {
// Default value of selectedStep being 1
currentStep = `step-${++this.selectedStep}`;
}
相关问题