【发布时间】:2017-04-02 04:07:41
【问题描述】:
我有一个自定义的FormFieldComponent,它封装了表单字段的 HTML 和错误显示逻辑:
@Component({
selector: 'field',
template: `
<div class="form-group">
<label class="control-label">{{label}}</label>
<ng-content></ng-content> <!-- Will display the field -->
<!-- Here, put error display logic -->
</div>
`
})
export class FormFieldComponent {
@Input() label: string; // Field label
@Input() theControl: FormControl; // Current form control, required to display errors
}
在FormFieldComponent 中,我需要一个FormControl 实例来显示错误。
然后我的表单如下所示:
<form [formGroup]="myForm">
...
<field label="Title" [theControl]="myForm.get('title')">
<input type="text" formControlName="title">
</field>
...
</form>
但我对上面的代码并不完全满意。如您所见,我在两个位置指定字段的键:在[theControl] 输入属性和formControlName 指令中。
如果我能写的话,代码会更简洁:
<field label="Title">
<input type="text" formControlName="title">
</field>
注意[theControl] 输入属性是如何消失的。 FieldComponent 应该能够获取它包含的 FormControl 实例,但是如何?
我曾尝试使用 @ContentChildren 装饰器来查询组件模板中的 FormControl 指令,但它不起作用:
export class FormFieldComponent {
@ContentChildren(FormControlDirective) theControl: any;
}
另一种选择是将字段的键作为输入传递给FormFieldComponent,然后让组件使用该键:
- 以编程方式将
formControlName指令应用于它包含的字段。 - 获取其父
<form>,访问相应的 FormGroup 实例,并从中提取 FormControl 实例。
【问题讨论】:
-
我不明白你在做什么。我的应用中有许多反应式表单,从未使用过 [control],我只使用 formControlName。
-
@John:
[control]不是 Angular 指令,它只是我给输入属性的名称。我会将[control]重命名为[theControl]以使其更明显。那么,您知道组件如何获取出现在其模板中的 FormControl 实例吗? -
你不能在
-
我的问题是,只要您可以通过实现
ControlValueAccessor创建自己的自定义输入,为什么要这样做? -
很高兴看到解决方案 n00dl3