【发布时间】: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>
【问题讨论】: