Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add *ngIf in a directive

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."

like image 237
Steven Avatar asked Jan 29 '23 21:01

Steven


1 Answers

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.

like image 191
Chris Baldwin Avatar answered Feb 01 '23 10:02

Chris Baldwin