【问题标题】:Angular Structural Directive with multiple parameters具有多个参数的角度结构指令
【发布时间】:2020-10-09 13:11:16
【问题描述】:

我无法使用结构指令来处理多个参数。


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

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>

【问题讨论】:

    标签: angular angular-directive


    【解决方案1】:

    在结构指令中,您不能在输入中使用括号。而且,当您的第一个输入与 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>
    

    【讨论】:

    • 谢谢,@emihud。我根据对我有用的方法做了一些小改动,但现在很好!
    猜你喜欢
    • 2018-09-17
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2017-06-06
    • 1970-01-01
    相关资源
    最近更新 更多