Angular 具有多个参数的结构指令

Angular Structural Directive with multiple parameters

我无法获得使用多个参数的结构指令。


此代码有效,记录了两个参数,但它不是结构指令:

import { Input, Directive, AfterViewInit } from "@angular/core";
import { ProfileModel } from "../auth/auth.models";

@Directive({
    selector: 'hasRole'
})
export class HasRoleDirective implements AfterViewInit {

    @Input()
    public profile: ProfileModel;

    @Input()
    public roleName: string;

    ngAfterViewInit(): void {
        console.log(this.roleName, this.profile);
    }
}

使用此标记:

<hasRole [roleName]="'Admini'" [profile]="profile">A</hasRole>

但是这段代码不起作用,即当我切换到结构指令时,AfterViewInit 中的值丢失了:

import { Input, Directive, AfterViewInit, ViewContainerRef, TemplateRef } from "@angular/core";
import { ProfileModel } from "../auth/auth.models";

@Directive({
    selector: '[hasRole]'
})
export class HasRoleDirective implements AfterViewInit {

    @Input()
    public profile: ProfileModel;

    @Input()
    public roleName: string;

    constructor(
        private view: ViewContainerRef,
        private templateRef: TemplateRef<any>,
    ) {
    }

    ngAfterViewInit(): void {
        console.log(this.roleName, this.profile);

        //if (this.profile.roles.find(o => o === this.roleName)) {
        //    this.viewContainer.createEmbeddedView(this.templateRef);
        //} else {
        //    this.viewContainer.clear();
        //}
    }
}

使用此标记:

<div *hasRole [roleName]="'Admini'" [profile]="profile">A</div>

在结构指令中,您不能使用方括号输入。而且,当您的第一个输入与 Directive (hasRole)

同名时会更好

您的标记应如下所示:

<div *hasRole="'Admini';profile:'profile'"></div>

您的@Inputs 将是:

@Input()
public hasRole: string;

@Input()
public hasRoleProfile: ProfileModel;

或者您可以使用模板

<template [hasRole]="hasRole" [profile]="'profile'">
  </div></div>
</template>