我想用 angular-permisssion 实现类似的东西.并且需要控制元素的存在,我需要使用 Angular structural directive .
一开始,我认为这样的语法是可行的:
<h2 *permissionIf [permissionIfExcept]="'Read'">Except</h2>
但是,它不是那样工作的。
此外,官方指南只教您如何使用单输入编写自定义结构指令。 有了多输入,一些第三方教程涉及到一点。但那是使用 Angular 模板微语法来实现数据绑定(bind)。然后出现一个问题: 模板语法不支持纯键值输入:
<h2 *permissionIf="except: map.except;only: 'test'">Except</h2>
它扩展成这个(这是非法的):
<h2 template="permissionIf except: map.except;only: 'test'">Except</h2>
一个愚蠢的临时解决方案是添加无用的变量声明。
<h2 *permissionIf="let i;except: map.except;only: 'test'">Except</h2>
另一种不方便的方法是使用模板元素来包装代码。
<template permissionIf [permissionIfExcept]="'Read'">
<h2>Except</h2>
</template>
以上都还不够接受。但我找不到更好的方法来解决它。
希望有大佬给点建议:).
最佳答案
输入名称都需要以指令的选择器为前缀,然后是输入名称大写(即permissionIfExcept
)。示例:
@Directive({
selector: '[permissionIf]'
})
export class PermissionIfDirective implements AfterContentInit {
private _permissionIf:string[];
@Input()
set permissionIf(value: string[]) {
this._permissionIf=value;
console.log('permissionIf: ', value);
}
private _except:string;
@Input()
set permissionIfExcept(value: string) {
this._except = value;
console.log('except: ', value);
}
}
将它们与“*”语法一起使用:
<div *permissionIf="permissions;except:'Read'"></div>
注意这里您使用的是前缀 uncapitalized 之后的名称(即 except
)。另请注意 :
在作业中。
显式语法(使用 template
)如下所示:
<template [permissionIf]="permissions" [permissionIfExcept]="'Read'">
</div></div>
</template>
但使用 <ng-container>
它可能看起来像
<ng-container *permissionIf="permissions;except:'Read'">
<div></div>
</ng-container>
另见 source的 NgFor
举个例子。
关于javascript - 如何使用具有多个输入的 Angular 结构指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41789702/