Search code examples
angulartypescriptangular-ng-if

*ngIf equivalent in TypeScript code


How is it possible check if the component property is undefined within the TypeScript code, in a method for instance?

In .html component template it is possible to do such check as a conditional on displaying html elements. To avoid the diplay in case they do not exist or not initialized yet.

<div *ngIf="exampleComponentProperty"></div>

Is it possible to do the same check in .ts? How would the expression look then?

if (this.exampleComponentProperty != null) {
// some code...
}

did not seem to work.


Solution

  • You can try condition with avoiding all the possibilities :

    In TS :

    if (this.exampleComponentProperty && this.exampleComponentProperty != undefined && this.exampleComponentProperty != null) {
        // write code...
    }
    

    In HTML :

     <div *ngIf="exampleComponentProperty && exampleComponentProperty != undefined && exampleComponentProperty != null"></div>