[英]Setting a custom attribute directive in Angular2
I am trying to set a costume attribute directive to an input but I couldn't find the way to do it. 我正在尝试为输入设置服装属性指令,但找不到方法。
My directive is the following 我的指令如下
@Directive({
selector: '[disable-paste]'
})
export class DisablePaste {
constructor(private _elementRef:ElementRef) {
this._elementRef.nativeElement.onpaste = (e:any) => {
e.preventDefault();
}
}
}
If I just put the directive by its own in the input, it works. 如果我只是将指令本身放入输入中,那么它将起作用。 But when I try to use it "conditionally" it doesn't.
但是,当我尝试“有条件地”使用它时却没有。 I tried all these:
我尝试了所有这些:
<input [disable-paste]="doNotAllowPaste" ... />
<input disable-paste="doNotAllowPaste" ... />
<input [attr.disable-paste]="doNotAllowPaste" ... />
I think you need an input property in order to conditionally execute your logic, whenever the input property value changes: 我认为您需要一个输入属性,以便每当输入属性值发生更改时有条件地执行逻辑:
@Directive({
selector: '[disable-paste]'
})
export class DisablePaste {
@Input('disable-paste') disablePaste:boolean;
constructor(private _elementRef:ElementRef) {}
ngOnChanges() {
if(this.disablePaste) {
this._elementRef.nativeElement.onpaste = (e:any) => {
e.preventDefault();
}
} else {
this._elementRef.nativeElement.onpaste = null;
}
}
}
You coulsd try this: 您可以尝试以下操作:
@Directive({
selector: '[disable-paste]'
})
export class DisablePaste {
@Input('disable-paste')
disablePaste:any;
constructor(private _elementRef:ElementRef) {
this._elementRef.nativeElement.onpaste = (e:any) => {
e.preventDefault();
}
}
}
If you use [...]
, you will get an object corresponding to the evaluation of the specified expression. 如果使用
[...]
,将获得一个与指定表达式的求值相对应的对象。 Without them, a string value. 没有它们,则为字符串值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.