在Angular中,可以使用@ViewChild装饰器来获取子组件的引用,并通过该引用来更新父组件中的表单值。以下是一个示例代码:
父组件(parent.component.ts):
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
@ViewChild(ChildComponent) childComponent: ChildComponent;
updateFormValues() {
// 通过子组件引用来更新父组件中的表单值
this.childComponent.updateFormValues();
}
}
子组件(child.component.ts):
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-child',
template: `
`
})
export class ChildComponent {
form: FormGroup;
constructor() {
this.form = new FormGroup({
name: new FormControl(''),
age: new FormControl('')
});
}
updateFormValues() {
// 更新表单值
this.form.patchValue({
name: 'John',
age: 30
});
}
}
在父组件中使用@ViewChild装饰器来获取子组件的引用,然后可以调用子组件的方法来更新父组件中的表单值。在子组件中,使用FormGroup和FormControl来定义表单,并通过patchValue方法来更新表单值。
在父组件的模板中,通过点击按钮来调用updateFormValues方法,从而更新表单值。