Angular - 可以有条件地应用指令吗?

Angular - Possible to apply a directive conditionally?

我需要根据 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>

Angular2+之后,无法有条件地应用指令。 所以需要像你提到的那样复制代码。

只需将参数传递给您的指令(假设它是您的指令)。有点像。

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