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

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

问题描述

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

对于一个简单的实验,我尝试了这个:

@Directive({选择器:'[lhUserHasRights]'})导出类 UserHasRightsDirective 实现 OnInit、OnDestroy {构造函数(私有 el:ElementRef){}ngOnInit(): 无效 {this.el.nativeElement.setAttribute("*ngIf", "false");}...

,但是没有用.浏览器显示错误ERROR DOMException: Failed to execute 'setAttribute' on 'Element': 'ngIf' is not a valid attribute name."

解决方案

以下建议基于 StructuralAngular 文档中的指令示例.

@Directive({选择器:'[lhUserHasRights]'})导出类 UserHasRightsDirective 实现 OnInit、OnDestroy {private hasRights = false;私有 hasView = false;构造函数(私有模板引用:模板引用<任何>,私有视图容器:ViewContainerRef) {}ngOnInit(): 无效 {如果 (this.hasRights && !this.hasView) {this.viewContainer.createEmbeddedView(this.templateRef);this.hasView = true;} else if (!this.hasRights && this.hasView) {this.viewContainer.clear();this.hasView = false;}}...

现在这是您可能需要连接的其他管道,具体取决于您必须如何使用指令.例如你想像这样使用它

...

...

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

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

解决方案

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.

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

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