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" ... />
Cœur
39k25 gold badges207 silver badges282 bronze badges
asked Mar 28, 2016 at 18:45
Hernan Pintos
1752 silver badges9 bronze badges
2 Answers 2
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;
}
}
}
answered Mar 28, 2016 at 21:53
Mark Rajcok
365k114 gold badges501 silver badges495 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Mar 28, 2016 at 18:48
Thierry Templier
203k44 gold badges407 silver badges366 bronze badges
2 Comments
Hernan Pintos
This is a good alternative, but I wanted to know if there was a way of conditionally render that directive without having to add an input to it.
Thierry Templier
Just a silly question: why don't apply the directive if you don't have the behavior. The directive contains several things. Just try to understand better your issue ;-) Angular2 commonly mixes another attribute to disable it. For example:
selector: 'form:not([ngNoForm]):not([ngFormModel]),ngForm,[ngForm]'. See github.com/angular/angular/blob/master/modules/angular2/src/….lang-js