在指令中动态添加* ngIf [英] Dynamically add *ngIf in a directive

查看:109
本文介绍了在指令中动态添加* ngIf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何动态地将* ngIf添加到用属性指令修饰的元素上?

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");
    }

    ...

,但是没有用.浏览器显示了一个错误"错误DOMException:无法在'Element'上执行'setAttribute':' ngIf'不是有效的属性名称."

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

推荐答案

以下建议基于结构Angular文档中的指令示例.

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

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

我建议您阅读上面链接中的文档部分.

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

这篇关于在指令中动态添加* ngIf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆