Search code examples
angularangular-ng-if

Angular's *ngIf does not show the component's template


I haven't worked with Angular for a while, but I remember I used to trigger the elements using *ngIf. Now, I'm not sure what's wrong. When I trigger the function straight <button (click)="play()">...</button> it works, but I don't see the point why it's not working using object's property. When using object's property the method is being triggered, but the value never gets changed (is it not the same instance or something?).

component:

public showPlay: boolean = false;
public arr: Array<Object> = [
    {clickHandler: this.play}
];

play(): void {
    this.showPlay = !this.showPlay;
}

template:

<button *ngFor="let button of arr" (click)="button.clickHandler()">Click</button>
<play-interface *ngIf="showPlay"></play-interface>

Solution

  • You can do something like this,

     <button *ngFor="let button of arr" (click)="self[button.clickHandler]()">Click</button>
     <div *ngIf="showPlay">hi</div>
    

    and in template,

    export class AppComponent {
    public showPlay: boolean = false;
    public arr: Array<Object> = [
        {clickHandler: 'play'}
    ];
    get self() { return this; }
    
    play(): void {
        this.showPlay = !this.showPlay;
    }
    

    DEMO