mat*_*th5 1 typescript angular angular-reactive-forms angular11
我正在以这种方式使用父表单和子组件表单。/sf/answers/4151721101/
当父表单提交了按钮 Ng 时,如何让子组件知道?ParentForm 变量在子组件中作为变量。有没有办法,我可以将parentFormGroup 作为一个事件来告诉我?
当子窗体知道时,我想计算一些复杂的值(不在窗体中),并将它们发送到父组件。
父组件:
ngOnInit() {
this.parentForm = this.fb.group({
'customerName': [null, [Validators.required]],
'phoneNumber': [null, [Validators.required]],
})
<form [formGroup]="parentForm" (ngSubmit)="onSubmit()">
<app-child [form]="parentForm"></app-child>
<button type="submit">Purchase</button>
</form>
Run Code Online (Sandbox Code Playgroud)
子组件:
需要知道在这个组件中,parentForm 是什么时候提交的。
@Input() parentForm: FormGroup;
ngOnInit() {
this.parentForm.addControl('address', new FormControl(Validators.required));
this.parentForm.addControl('city', new FormControl(Validators.required));
}
Run Code Online (Sandbox Code Playgroud)
您可以在子组件中注入FormGroupDirective,然后在子组件中订阅 ngOnSubmit 事件以监听父表单提交。
子组件.ts
constructor(private fg: FormGroupDirective){
this.fg.ngSubmit.subscribe(()=>{
console.log('listen submit');
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5879 次 |
| 最近记录: |