I'm using Angular 5.2.10. Suppose we have the following template:
<mat-form-field *appEntityValidate>
<input
matInput
type="text"
placeholder="Some input">
</mat-form-field>
In EntityValidateDirective
, we need to get an instance of MatFormField
it's apllied to.
I've tried a solution suggested here, i.e. simply inject MatFormField
:
@Directive({
selector: "[appEntityValidate]"
})
export class EntityValidateDirective {
constructor(
private readonly matFormField: MatFormField
) {
const dfg = 0;
}
}
, but I'm getting an exception from Angular:
No provider for MatFormField!
Here is Stackblitz.
I suspect that this doesn't work because my directive is structural one rather than an attribute one.
So, how to access host component in a structural directive then?
UPDATE: In attempt to address concern raised by @yurzui in comments. Specifically, that MatFormField
isn't really a host component in this case, since the above markup gets de-sugarized into something like this:
<ng-template appEntityValidate>
<mat-form-field>
<input matInput type="text" placeholder="Some input">
</mat-form-field>
</ng-template>
Thus, MatFormField
becomes a child of the element which EntityValidateDirective
is applied to.
To cover this, I've also tried the following:
@Directive({
selector: "[appEntityValidate]"
})
export class EntityValidateDirective implements AfterContentInit, AfterViewInit {
@ContentChild(MatFormField) content;
@ViewChild(MatFormField) view;
public ngAfterViewInit() {
const view = this.view;
}
public ngAfterContentInit() {
const content = this.content;
}
}
But both content
and view
are undefined
in the corresponding lifecycle hook methods.