如何使用动态名称创建Angular 2自定义属性指令
How can I create Angular 2 custom attribute directive with dynamic name?
我想以与本例中使用的"attr"、"class"、"style"等内置指令相同的方式创建自定义属性指令:
<div [style.width.px]="mySize">
此处的文档仅描述具有固定指令名称的情况。所以问题是:
我应该如何为这样的指令指定选择器?
如何检索指令名称的变量部分?
或者它可能根本不可能,只用于内置指令?
尽管在@Günter的检查中几乎肯定不可能做到这一点。
nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp PLUNKER&neArr
但是,如果您只想要一个与style
几乎类似的指令,这可能会对您有所帮助。
用法:
<h2 [customStyle]="['width.px', mysize]" >Hello {{name}}</h2>
自定义指令:
@Directive({
selector: '[customStyle]',
inputs: ['style:customStyle']
})
export class CustomDir{
style;
constructor(private elRef: ElementRef){
}
ngAfterViewInit(){
if(this.style){
const prop = this.style[0].split('.')[0];
const unit = this.style[0].split('.')[1];
const val = this.style[1];
this.elRef.nativeElement.style[prop] = val + (unit || '');
}
}
}
据我所知,这是不支持的,也没有计划。
或者它可能根本不可能,只用于内置指令?
此语法与指令无关,它是内置的绑定语法。
相关文章:
- 向动态生成的DOM添加Angular自定义指令
- 设置自动分隔符的自定义属性
- 与ng attr myCustomAttribute匹配的自定义属性指令
- 获取自定义属性的值
- 如何创建自定义属性以添加if.bind
- 动态更新Angular2指令中自定义属性的值
- 使用jQuery更改输入字段的自定义属性
- 在 Javascript 生成的列表中,如何将自定义属性添加到 标记
- 设置 HTML 自定义属性与在 ID 属性中存储信息
- 是否可以在 Polymer 中的
节点上使用自定义属性以获得漂亮的 API - 为什么克隆节点排除自定义属性
- 将自定义属性添加到 vuejs 组件
- 使用原型对象向javascript对象添加自定义属性和方法的建议
- 正在设置自定义属性名称
- Angular 2 Component自定义属性在构造函数中为null
- 刷新 Angular 中自定义属性指令的元素
- ASP.NET MVC&Angular:当会话Cookie过期时,自定义属性/ActionFilter,希望它重
- Angular自定义属性指令应该被另一个指令取代
- 如何将Angular js ngOptions与自定义属性一起使用
- 如何使用动态名称创建Angular 2自定义属性指令