在Angular中,ngForm
是一个内置的表单指令,它提供了一种简便的方式来处理表单数据绑定和验证。如果你想将 ngForm
传递给子组件,可以通过以下几种方式实现:
@Input()
装饰器import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-parent',
template: `
<form #parentForm="ngForm" (ngSubmit)="onSubmit(parentForm)">
<app-child [childForm]="parentForm"></app-child>
<button type="submit">Submit</button>
</form>
`
})
export class ParentComponent {
onSubmit(form: NgForm) {
console.log(form.value);
}
}
import { Component, Input } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-child',
template: `
<input type="text" name="childInput" formControlName="childInput" />
`
})
export class ChildComponent {
@Input() childForm: NgForm;
}
ViewChild
和 AfterViewInit
import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
<form #parentForm="ngForm" (ngSubmit)="onSubmit(parentForm)">
<app-child></app-child>
<button type="submit">Submit</button>
</form>
`
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) childComponent: ChildComponent;
ngAfterViewInit() {
this.childComponent.childForm = this.form;
}
form = new NgForm({});
onSubmit(form: NgForm) {
console.log(form.value);
}
}
import { Component, Input } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-child',
template: `
<input type="text" name="childInput" formControlName="childInput" />
`
})
export class ChildComponent {
@Input() childForm: NgForm;
}
这种方法常用于需要在父组件和子组件之间共享表单数据和验证状态的场景。例如,你可能有一个复杂的表单,其中某些部分在子组件中处理,而你需要父组件来处理整个表单的提交。
formControlName
或 ngModel
。NgForm
实例。ngForm
的 controls
属性。通过以上方法,你可以将 ngForm
传递给子组件,并在子组件中使用它来处理表单数据和验证。
领取专属 10元无门槛券
手把手带您无忧上云