Angular2 check if object has peoperty inside *ngIf

Pratap A.K picture Pratap A.K · Mar 31, 2017 · Viewed 14.7k times · Source
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 is like below

selectedElement: Element;

now in html how can I check if the object is having property 'type' or not?

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

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Mar 31, 2017

I guess this should do what you want:

*ngIf="hasProp(selectedElement, 'type')"
hasProp(o, name) {
  return o.hasOwnProperty(name);
}