I have a custom FormFieldComponent
that encapsulates the HTML and error display logic for a form field:
@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
}
In FormFieldComponent
, I need an instance of the FormControl to display errors.
My form then looks like this:
<form [formGroup]="myForm">
...
<field label="Title" [theControl]="myForm.get('title')">
<input type="text" formControlName="title">
</field>
...
</form>
But I'm not entirely satisfied with the above code. As you can see, I am specifying the field's key in two locations: in the [theControl]
input property and in the formControlName
directive.
The code would be more concise if I could just write:
<field label="Title">
<input type="text" formControlName="title">
</field>
Notice how the [theControl]
input property is gone. The FieldComponent
should be able to get a hold of the FormControl instance it contains, but how?
I have tried using the @ContentChildren
decorator to query the component's template for FormControl directives, but it doesn't work:
export class FormFieldComponent {
@ContentChildren(FormControlDirective) theControl: any;
}
Another option would be to pass the field's key as an input to FormFieldComponent
and then let the component use that key to:
- Programmatically apply the
formControlName
directive to the field it contains. - Get a hold of its parent
<form>
, access the corresponding FormGroup instance, and extract the FormControl instance from that.
[control]
is not an Angular directive, it's just the name I gave to my input property. I'll rename[control]
to[theControl]
to make it more obvious. So, do you know how a component can get a hold of the FormControl instances that appear in its template? – AngularChefControlValueAccessor
? – n00dl3