Accessing a typescript variable inside ngif statement in angular

1.2k Views Asked by At

I have a variable in ts. I wanna access it inside ngif.

TS:

  public data:string

HTML:

  <td> 
      <div *ngIf="data === 'BALL' ; else noplay" >{{ play}}</div>
      <ng-template #noplay> {{gotohome}} 
     </ng-template>
  </td>

What I am doing is that if the variable data has value "BALL" I will display a value in table using string interpolation and if condition is not met a different value will be shown. I am findinfg it difficult to access the data variable from typescript

A sample stackblitz link

https://stackblitz.com/edit/angular-ivy-c6zyqg?file=src%2Fapp%2Fapp.component.html

2

There are 2 best solutions below

0
On BEST ANSWER

You are using method get() for assigning value to variable data. But that method is not invoked anywhere. That's causing the issue.

I've updated stackblitz by initializing value with declaration ad it works.

https://stackblitz.com/edit/angular-ivy-g5a852?file=src%2Fapp%2Fapp.component.ts

If you want to use getter, refer the below stackblitz.

https://stackblitz.com/edit/angular-ivy-wn8ccz?file=src%2Fapp%2Fapp.component.ts

0
On

The getter is defined incorrectly, use the following syntax:

  _data;

  get data() {
    return this._data = "BALL";
  }