Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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>
like image 795
Pratap A.K Avatar asked Mar 31 '17 09:03

Pratap A.K


People also ask

How do I check if an object is empty in ngIf?

Just for readability created library ngx-if-empty-or-has-items it will check if an object, set, map or array is not empty.

How do you check if an object contains a property in angular?

Using myObject. hasOwnProperty('prop') is a great way of accessing the Object's keys directly, which does not look into the Object's prototype - hooray, this is great for specific use cases. hasOwnProperty returns a Boolean for us on whether a property exists.

What is the use of * ngIf in angular2?

The *ngIf directive is most commonly used to conditionally show an inline template, as seen in the following example. The default else template is blank.

What is * in * ngIf?

The * syntax means that ngIf is a structural directive, meaning that it affects the structure of the page.


2 Answers

I guess this should do what you want:

*ngIf="hasProp(selectedElement, 'type')"
hasProp(o, name) {
  return o.hasOwnProperty(name);
}
like image 51
Günter Zöchbauer Avatar answered Oct 06 '22 08:10

Günter Zöchbauer


You can do it simply in the 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>  
like image 41
Sniper Avatar answered Oct 06 '22 08:10

Sniper