Hernan Pintos
Hernan Pintos

Reputation: 175

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

Upvotes: 1

Views: 240

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364697

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; 
    }
  }
}

Upvotes: 3

Thierry Templier
Thierry Templier

Reputation: 202196

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.

Upvotes: 1

Related Questions