-->

Dynamically add *ngIf in a directive

2019-05-14 04:40发布

问题:

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.