Reputation: 415
In AngularJS we used to have the pre
and post
functions, and the ability to $compile
templates when needed. There is no way of doing this in Angular (2+), is there?
Specifically, what I want to achieve is, having a template like this:
<form myDirective>
<input type="text" />
<input type="text" />
</form>
Make myDirective
add dynamically another directive (say anotherDirective
) to all the host's children of type input
. Is that possible somehow?
Upvotes: 0
Views: 1557
Reputation: 7607
No it's not possible. You cannot assign a directive dynamically, be it in another directive or a full component (a component is considered a directive with a template in Angular).
The only way to dynamically manipulate hard (eg not CSS) DOM properties is by using Renderer2 and accessing the host's element's children in your myDirective
like this:
constructor(private hostEl: ElementRef){}
ngOnInit() {
if(hostEl.nativeElement.children.length) {
hostEl.nativeElement.children.forEach(el => {if (isInput(el) { useRenderer2InSomeWay(el) })})
}
}
But what I would do is either to put anotherDirective
in each input directly, so you don't have to access children or (even better) consider not using a directive at all but just define a wrapper component for <input>
:
<my-input-wrapper
<input
[config]="someConfigToApplyToInputInside"
[formControlName]="'foobar'">
</input>
</my-input-wrapper>
and in the MyInputWrapperComponent:
@ContentChildren('input') inputs: QueryList<any>;
With ContentChild/ContentChildren you can access FormControls from the surrounding component but still delegate ui-stuff like custom placeholders and icons you want to have in the input, to the wrapper-component.
Upvotes: 3