angular - 具有多个参数的角度结构指令
问题描述
我无法使用结构指令来处理多个参数。
此代码有效,记录了两个参数,但它不是结构指令:
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>
解决方案
在结构指令中,您不能在输入中使用括号。而且,当您的第一个输入与指令(hasRole)具有相同的名称时会更好
您的标记应如下所示:
<div *hasRole="'Admini';profile:'profile'"></div>
您的 @Inputs 将是:
@Input()
public hasRole: string;
@Input()
public hasRoleProfile: ProfileModel;
或者你可以使用模板
<template [hasRole]="hasRole" [profile]="'profile'">
</div></div>
</template>
推荐阅读
- symfony - Symfony Webpack Encore,多个 JS/CSS 文件到一个文件
- qt - 如何将 mbtiles 转换为 .osm.pbf
- javascript - 如何编写 if 语句的第一行来测试时钟是否在点上的一个小时
- php - 如何阅读邮件正文
- vue.js - Vue js不能拖动输入类型文件
- spring-boot - Spring Mail Sender 使用 Gmail SMTP 错误。我该如何解决?
- javascript - 为什么尽管存在终止条件,但无限循环仍然存在?
- android - 无法在 MacOS 中使用 Buildozer 构建 kivy (python 2) apk [Errno 套接字错误] [SSL: TLSV1_ALERT_PROTOCOL_VERSION]
- python - Django 和 TinyMCE: NameError: name 'url' is not defined
- swift - 在 Swift 中的 ViewController 之间共享设备 CLLocation 的最佳方法是什么?