如何在多个输入中使用Angular结构指令 [英] How to use Angular structural directive with multiple inputs
问题描述
我想实现与角度许可类似的东西.为了控制元素的存在,我需要使用角度结构指令.
I want to implement something similar with angular-permisssion. And with requirement to control the element's existance, I need to use angular structural directive.
一开始,我认为这样的语法会起作用:
At the beginning, i think such syntax would work:
<h2 *permissionIf [permissionIfExcept]="'Read'">Except</h2>
但是,这种方式行不通.
However, it doesn't work that way.
此外,该官方指南仅教您如何使用单个输入编写自定义结构指令. 对于多输入,一些第三方教程涉及一些内容.但这是使用角度模板微语法来实现数据绑定.然后发生一个问题: 模板语法不支持纯键值输入:
Moreover, the offical guide only teach you how to write custom structural directive with single input. With multi-inputs, some third-party tutorials involve a bit. But that's using the angular template micro-syntax to achieve data binding. Then one problem occurs: template syntax doesn't support pure key-value inputs:
<h2 *permissionIf="except: map.except;only: 'test'">Except</h2>
它扩展为此(非法):
<h2 template="permissionIf except: map.except;only: 'test'">Except</h2>
一个愚蠢的临时解决方案是添加一个无用的变量声明.
A stupid temporary solution is add a useless variable declaration.
<h2 *permissionIf="let i;except: map.except;only: 'test'">Except</h2>
另一种不便的方法是使用模板元素包装代码.
Another inconvenient way is to use template element to wrap the code.
<template permissionIf [permissionIfExcept]="'Read'">
<h2>Except</h2>
</template>
以上所有内容都不足够.但是我找不到解决该问题的方法.
The above all are not accepetable enough. But I can't find a bette way to resolve it.
希望有些人可以提出一些建议:).
Hope some guys can give some suggestion:).
推荐答案
输入名称都必须以指令的选择器作为前缀,后跟输入名称大写(即permissionIfExcept
).示例:
The input names need all to be prefixed with the selector of the directive, followed by the input name capitalized (i.e. permissionIfExcept
). Example:
@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);
}
}
要以'*'语法使用它们:
To use them with the '*' syntax:
<div *permissionIf="permissions;except:'Read'"></div>
请注意,此处您使用的是前缀 uncapitalized (即except
)之后的名称.另请注意作业中的:
.
Note here you're using the name following the prefix uncapitalized (i.e. except
). Also note the :
in the assignment.
显式语法(使用template
)如下所示:
The explicit syntax (using template
) would look like this:
<template [permissionIf]="permissions" [permissionIfExcept]="'Read'">
</div></div>
</template>
但使用<ng-container>
可能看起来像
<ng-container *permissionIf="permissions;except:'Read'">
<div></div>
</ng-container>
另请参见源(例如NgFor
).
这篇关于如何在多个输入中使用Angular结构指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!