简体   繁体   中英

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>

I guess this should do what you want:

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

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>  

除了Günter Zöchbauer所说的:

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM