11
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>
Pratap A.K
  • 4,337
  • 11
  • 42
  • 79

4 Answers4

17

I guess this should do what you want:

*ngIf="hasProp(selectedElement, 'type')"
hasProp(o, name) {
  return o.hasOwnProperty(name);
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
10

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>  
Sniper
  • 109
  • 1
  • 3
  • Using a function like that inside a template is not recommended. On change detection the method will be called each time. Using a pipe like suggested in @yannic his answer would be preferable (see https://stackoverflow.com/a/64928306/1697459). – Wilt Oct 26 '21 at 06:43
7

in addition to what Günter Zöchbauer said:

*ngIf="selectedElement && selectedElement['type']"
Community
  • 1
  • 1
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37
4

A pipe would be the most performant option in that case.

Ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'hasProp',
})
export class HasPropPipe implements PipeTransform {
  transform(object: object, prop: string): boolean {
    return object.hasOwnProperty(prop);
  }
}

Template:

<button *ngIf="option | hasProp: 'value'">Yay!</button>
yannic
  • 41
  • 2