要获取对投影的 FormGroup 的访问权限,需要使用 @ViewChild 装饰器和 ngAfterViewInit 生命周期钩子。下面是一个示例解决方案:
在父组件中,使用 @ViewChild 装饰器来引用投影的子组件,并在 ngAfterViewInit 生命周期钩子中获取 FormGroup 对象。代码如下:
import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-parent',
template: `
`,
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) childComponent: ChildComponent;
form: FormGroup;
ngAfterViewInit() {
this.form = this.childComponent.form;
}
}
在子组件中,使用 @Input 装饰器将 FormGroup 对象传递给父组件,并将其保存在一个公共属性中。代码如下:
import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-child',
template: `
`,
})
export class ChildComponent {
@Input() form: FormGroup;
}
使用上述代码,父组件可以通过访问 childComponent.form 来获取对投影的 FormGroup 的访问权限。