1

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" ... />

2 Answers 2

3

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; 
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

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.
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/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.