【发布时间】:2019-03-01 13:40:55
【问题描述】:
我有一个父组件,它会在单击按钮时更改作为@Input() 传递的子窗体。我使用ngIf来渲染子组件,但是当我点击更改表单时,子组件并没有被销毁并重新创建。
parent.component.ts
form: FormGroup;
showChildForm: boolean;
num: number;
ngOnInit(){
this.showChildForm = false;
this.num = 1;
this.form = new FormGroup({group:{'name', new FormControl('name'+this.num,[])}})
}
changeForm(){
this.num += 1;
this.showChildForm = true;
this.form = new FormGroup({group:{'name', new FormControl('name'+this.num,[])}})
}
parent.component.html
<button (click)="changeForm()"></button>
<child *ngIf="showChildForm" [form]="form"></child>
child.component.ts
@Input() form: FormGroup;
child.component.html
<form [formGroup]="form">
<input type="text" [formControl]="form.get('name')"/>
</form>
【问题讨论】:
-
我没有时间真正考虑这么多,但我只是想指出您正在绑定到一个对象。然后父级更改对对象的引用而不实际更改对象。我不希望孩子意识到任何事情都发生了变化。
-
您提供的代码中没有 ngIf。请在堆栈闪电战中重现问题。
-
@danday74 哈哈
-
@danday74 很抱歉。我刚刚添加了它。
-
您不能使用 *ngIf 来销毁正在被另一个元素使用的子元素。我昨天真的发现了
标签: angular angular6 form-control