AngularOne
AngularOne

Reputation: 2860

Using angular 2 directive inside component template is not being rendered on a change

Take for example this simplae component template:

<div [tooltip]="text" [tooltipEnabled]="false">{{text}}</div>

Please notice tooltip is a directive working great, but when I use it inside other component template, while I change tooltipEnabled to be "true", I think the directive will notich the change and act, but its not.

What did I miss? It only work on first time load and any change after that will not be effacted? I can see the directive code runs, but it is reading tooltipEnabled proprety as false (the first load), while I see in html I did change it to be true.

Upvotes: 2

Views: 2539

Answers (1)

slaesh
slaesh

Reputation: 16917

Would be great if you could create a plunker..

Works fine: https://plnkr.co/edit/zElHdyZ5jbPGx5rFtlFI?p=preview

@Directive({
  selector: '[tooltip]'
})
export class TooltipDirective {
  private _tooltipEnabled: boolean;

  @Input()
  set tooltipEnabled(val: boolean) {
    console.log('value changed', val);
    this._tooltipEnabled = val;

    this._elementRef.nativeElement.style.backgroundColor = val ? '' : 'red'; // use Renderer for manipulations!!
  }

  @Input() tooltip: string;

  constructor(private _elementRef: ElementRef) {}
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 tooltip [tooltipEnabled]="toggleBool" (click)="toggleBool = !toggleBool">Hello {{name}} - click me</h2>
      <h2 tooltip [tooltipEnabled]="false">Should be red..</h2>
      <h2 tooltip [tooltipEnabled]="true">Should be white..</h2>
    </div>
  `,
})
export class App {
  name:string;

  public toggleBool = true;

  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}

Upvotes: 1

Related Questions