Angular 如何从父组件中的窗体接收值?
我有一个包含两个组件的模板。 这两个组件都是表单,将在模板中归档 现在我想从父组件中的表单接收值,并检查表单是否有效。然后我想启用按钮来提交这两个表单的值 模板如下所示:Angular 如何从父组件中的窗体接收值?,angular,typescript,Angular,Typescript,我有一个包含两个组件的模板。 这两个组件都是表单,将在模板中归档 现在我想从父组件中的表单接收值,并检查表单是否有效。然后我想启用按钮来提交这两个表单的值 模板如下所示: <section> <app-first-form></app-first-form> <app-second-form></app-second-form> <button [disabled]="first-form.invalid
<section>
<app-first-form></app-first-form>
<app-second-form></app-second-form>
<button [disabled]="first-form.invalid || second-form.invalid"> submit</button>
</section>
如果有人能告诉我怎么做就好了。谢谢 您可以通过两个元素上的
@Output()
或@ViewChild()
处理ParentComponent内部的所有内容来实现这一点。我建议使用@ViewChild
并在那里处理这两个表单
已创建一个供您参考
ParentComponent
@Component({...})
export class ParentComponent {
@ViewChild(Form1Component) form1: Form1Component;
@ViewChild(Form2Component) form2: Form2Component;
body: any;
constructor() {}
// Check if both forms are valid after validating that this.form1 and this.form2 already exists
get isFormValid(): boolean {
if (this.form1 && this.form2) return this.form1.form.valid && this.form2.form.valid;
}
save(): void {
const { value: form1Values } = this.form1.form; // Get form1 form values
const { value: form2Values } = this.form2.form; // Get form2 form values
// If both forms are valid, assign and merge result inside the body
if (this.isFormValid) this.body = {...form1Values, ...form2Values};
}
}
Form1和Form2组件都没有任何提交按钮,我们只有一个提交按钮,它位于ParentComponent上,用于检查表单状态并获取表单值
另一种方法是使用模板引用变量(与使用viewChild相同,但仅使用html)。记住,通过缺陷,组件的所有变量都是公共的。如果使用模板引用变量,则可以“获取”所有变量
<section>
<app-first-form #first></app-first-form>
<app-second-form #second></app-second-form>
<button [disabled]="first.form.invalid || second.form.invalid"> submit</button>
</section>
<pre>
{{first.form?.value}}
{{second.form?.value}}
</pre>
提交
{{first.form?.value}
{{second.form?.value}
在两个表单组件中使用@output并将事件发送给父组件,或者您可以使用@ViewChild decorator访问这两个表单,就像这正是我想要的一样。非常感谢!:)
@Component({...})
export class ParentComponent {
@ViewChild(Form1Component) form1: Form1Component;
@ViewChild(Form2Component) form2: Form2Component;
body: any;
constructor() {}
// Check if both forms are valid after validating that this.form1 and this.form2 already exists
get isFormValid(): boolean {
if (this.form1 && this.form2) return this.form1.form.valid && this.form2.form.valid;
}
save(): void {
const { value: form1Values } = this.form1.form; // Get form1 form values
const { value: form2Values } = this.form2.form; // Get form2 form values
// If both forms are valid, assign and merge result inside the body
if (this.isFormValid) this.body = {...form1Values, ...form2Values};
}
}
<section>
<app-first-form #first></app-first-form>
<app-second-form #second></app-second-form>
<button [disabled]="first.form.invalid || second.form.invalid"> submit</button>
</section>
<pre>
{{first.form?.value}}
{{second.form?.value}}
</pre>