访问结构指令

时间:2018-04-16 22:30:55

标签: html angular typescript

我正在使用Angular 5.2.10。假设我们有以下模板:

<mat-form-field *appEntityValidate>
    <input
        matInput
        type="text"
        placeholder="Some input">
</mat-form-field>

EntityValidateDirective中,我们需要获得MatFormField的实例。

我尝试过建议here的解决方案,即只需注入MatFormField

@Directive({
    selector: "[appEntityValidate]"
})
export class EntityValidateDirective {
    constructor(
        private readonly matFormField: MatFormField
    ) {
        const dfg = 0;
    }
}

,但我从Angular得到例外:

  

没有MatFormField的提供者!

这是Stackblitz

我怀疑这不起作用,因为我的指令是结构指令而不是属性指令。

那么,如何在结构指令中访问主机组件呢?

更新:试图解决@yurzui在评论中提出的问题。具体来说,在这种情况下,MatFormField实际上不是主机组件,因为上面的标记会被降级为以下内容:

    <ng-template appEntityValidate>
        <mat-form-field>
            <input matInput type="text" placeholder="Some input">
        </mat-form-field>
    </ng-template> 

因此,MatFormField成为EntityValidateDirective应用于的元素的子元素。

为了解决这个问题,我还尝试了以下方法:

@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;
    }
}

contentview在相应的生命周期钩子方法中都是undefined

0 个答案:

没有答案
相关问题