Angular2 check if object has peoperty inside * ngIf

export interface Element {    
    name: string;   
}

export class Room implements Element {
name: string; 
type:string
}

export class Hall implements Element {
name: string;
}

      

and my varibale type looks like below

selectedElement: Element;

      

now in html, how can I check if an object has a 'type' property or not?

<div *ngIf="selectedElement?.type">
my div
</div>

      

+3


source to share


3 answers


I think this should do what you want:

*ngIf="hasProp(selectedElement, 'type')"

      



hasProp(o, name) {
  return o.hasOwnProperty(name);
}

      

+6


source


You can do it simply in html:

<div *ngIf="selectedElement.hasOwnProperty('type')">
my div
</div>

      



or

<div *ngIf="selectedElement.hasOwnProperty('type');then 
showMyDiv">...</div>

<ng-template #showMyDiv> 
my div
</ng-template>  

      

+4


source


in addition to what Gunther Zochbauer said:

*ngIf="selectedElement && selectedElement['type']"

      

+3


source







All Articles