如何在Angular组件外部通过ng-content定义FormGroup控件
问题根因
Angular 表单指令的匹配逻辑发生在编译阶段,而非运行时:你在父组件模板中写的formControlName,编译时会在父组件的模板作用域内向上查找对应的FormGroup实例,此时父组件作用域内并没有你在Hello组件内部定义的FormGroup,哪怕运行时DOM最终被投影到form标签内部,编译阶段的校验也会失败,这就是报错的核心原因。
方案1:父组件显式绑定Hello组件暴露的FormGroup
这种改造成本最低,只需要两步:
- 将Hello组件内的FormGroup声明为公共属性,方便外部模板访问:
// hello.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'hello', templateUrl: './hello.component.html' }) export class HelloComponent implements OnInit { // 声明为public,允许外部模板访问 public fg: FormGroup; constructor(private fb: FormBuilder) {} ngOnInit() { this.fg = this.fb.group({ aaa: [''], bbb: [''], ccc: [''] }) } }
- 父组件模板中通过模板引用变量获取Hello组件实例,给投影的控件外层显式绑定FormGroup:
<!-- 父组件模板 --> <hello #hello1> <div fg-controls [formGroup]="hello1.fg"> <h1>Item 1</h1> aaa: <input formControlName="aaa" /><br /><br /> bbb: <input formControlName="bbb" /><br /><br /> ccc: <input formControlName="ccc" /> </div> </hello> <hello #hello2> <div fg-controls [formGroup]="hello2.fg"> <h1>Item 2</h1> aaa: <input formControlName="aaa" /><br /><br /> bbb: <input formControlName="bbb" /><br /><br /> </div> </hello>
方案2:使用ng-template传递内容(更优雅,无额外绑定)
将需要插入的表单控件封装为模板传入Hello组件,在Hello组件内部渲染模板,此时模板的作用域和Hello组件一致,不需要额外绑定FormGroup:
- Hello组件新增输入属性接收模板,模板内部渲染模板:
// hello.component.ts import { Component, OnInit, Input, TemplateRef } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'hello', templateUrl: './hello.component.html' }) export class HelloComponent implements OnInit { fg: FormGroup; // 接收外部传入的模板 @Input() controlTpl: TemplateRef<any>; constructor(private fb: FormBuilder) {} ngOnInit() { this.fg = this.fb.group({ aaa: [''], bbb: [''], ccc: [''] }) } }
<!-- hello.component.html --> <form [formGroup]="fg"> <!-- 渲染传入的模板 --> <ng-container *ngTemplateOutlet="controlTpl"></ng-container> <pre>{{fg.value | json}}</pre> </form>
- 父组件封装模板传入:
<!-- 父组件模板 --> <ng-template #tpl1> <h1>Item 1</h1> aaa: <input formControlName="aaa" /><br /><br /> bbb: <input formControlName="bbb" /><br /><br /> ccc: <input formControlName="ccc" /> </ng-template> <hello [controlTpl]="tpl1"></hello> <ng-template #tpl2> <h1>Item 2</h1> aaa: <input formControlName="aaa" /><br /><br /> bbb: <input formControlName="bbb" /><br /><br /> </ng-template> <hello [controlTpl]="tpl2"></hello>
内容的提问来源于stack exchange,提问作者haya
相关产品推荐
相关产品推荐

