【问题标题】:Angular - Possible to apply a directive conditionally?Angular - 可以有条件地应用指令吗?
【发布时间】:2020-09-15 12:51:57
【问题描述】:

我需要根据type 创建两个不同的ul。如果我有first 的类型,那么我想应用指令*dropdownMenu。否则,将没有下拉指令。

是否可以有条件地应用指令,这样就不会出现重复的代码?

    <ng-container *ngIf="type === 'first'">
      <ul *dropdownMenu item-directive [firstLevelItems]="items1" [secondLevelItems]="items2" [type]="type">
      </ul>
    </ng-container>

    <ng-container *ngIf="type !== 'first'">
      <ul item-directive [firstLevelItems]="items1" [secondLevelItems]="items2" [type]="type">
      </ul>
    </ng-container>

【问题讨论】:

    标签: angular dropdown angular-directive


    【解决方案1】:

    在 Angular 2+ 之后,无法根据条件应用指令。 所以需要复制你提到的代码。

    【讨论】:

    • 由于我找不到任何解决方法,我接受这个作为正确答案。谢谢。
    【解决方案2】:

    只需将参数传递给您的指令(假设它是您的指令)。类似的东西。

    <ul *dropdownMenu="type"></ul>
    
    @Directive({ selector: '[dropdownMenu]' })
    export class DropdownMenuDirective implements OnInit {
        private _type: string;
        
        constructor(
            private templateRef: TemplateRef<any>,
            private viewContainer: ViewContainerRef
        ) {}
    
        @Input()
        set dropdownMenu(type: string) {
            this._type = type
        }
    
        ngOnInit() {
            if (this._type === 'first') {
                this.viewContainer.clear() // to clear the view
            } else {
                this.viewContainer.createEmbeddedView(this.templateRef); // to create it
            }
        }
    }
    

    【讨论】:

    • 感谢您的回答。但该指令属于 ngx-bootstrap 下拉模块。所以,我不能玩内部结构。
    猜你喜欢
    • 2017-11-19
    • 2016-08-29
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 2016-09-26
    • 2018-11-16
    • 2015-07-11
    • 2013-09-24
    相关资源
    最近更新 更多