首页 > 解决方案 > 具有多个参数的角度结构指令

问题描述

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


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

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>

标签: angularangular-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>

推荐阅读