Dynamically add *ngIf in a directive

淺唱寂寞╮ 提交于 2019-12-07 15:39:46

问题


how can I dynamically add an *ngIf to an element that's decorated with an attribute directive?

For a simple experiment, I tried this:

@Directive({
    selector: '[lhUserHasRights]'
})
export class UserHasRightsDirective implements OnInit, OnDestroy {
    constructor(private el: ElementRef) {
    }

    ngOnInit(): void {
        this.el.nativeElement.setAttribute("*ngIf", "false");
    }

    ...

, but it didn't work. The browser showed me an error "ERROR DOMException: Failed to execute 'setAttribute' on 'Element': 'ngIf' is not a valid attribute name."


回答1:


The following suggestion is based on the Structural Directives example from the Angular documentation.

@Directive({
    selector: '[lhUserHasRights]'
})
export class UserHasRightsDirective implements OnInit, OnDestroy {
    private hasRights = false;
    private hasView = false;

    constructor(private templateRef: TemplateRef<any>,
                private viewContainer: ViewContainerRef) {
    }

    ngOnInit(): void {
        if (this.hasRights && !this.hasView) {
            this.viewContainer.createEmbeddedView(this.templateRef);
            this.hasView = true;
        } else if (!this.hasRights && this.hasView) {
            this.viewContainer.clear();
            this.hasView = false;
        }
    }

    ...

Now this is some other plumbing you may have to hook up depending on how you have to use your directive. For example do you want to use it like this

<div *lhUserHasRights>...</div>

or

<div *lhUserHasRights="condition">...</div>

I would suggest reading the section of the documentation in the link above.



来源:https://stackoverflow.com/questions/45403221/dynamically-add-ngif-in-a-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!