Angular 中的 FormGroup 是一个用于管理表单控件的组件,而 ng-content 是用于在组件中插入内容的指令。
以下是一个示例代码,演示了如何使用 FormGroup 和 ng-content:
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
name: new FormControl('')
});
}
}
import { Component, ContentChild, AfterContentInit } from '@angular/core';
import { FormControlName } from '@angular/forms';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements AfterContentInit {
@ContentChild(FormControlName) ageControl: FormControlName;
ngAfterContentInit() {
if (this.ageControl) {
this.myForm.addControl('age', this.ageControl.control);
}
}
}
这样,就可以在组件中使用 ng-content 插入额外的内容,并将其与 FormGroup 中的表单控件进行绑定。