Angular2检查对象是否在* ngIf内有peoperty

时间:2017-03-31 09:12:50

标签: angular typescript angular2-components ngif

export interface Element {    
    name: string;   
}

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

export class Hall implements Element {
name: string;
}

我的varibale类型如下所示

selectedElement: Element;

现在在html中如何检查对象是否具有属性' type'不是吗?

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

4 个答案:

答案 0 :(得分:8)

我想这应该做你想要的:

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

答案 1 :(得分:6)

您只需在html中执行此操作:

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>


<div id="map"></div>

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

答案 2 :(得分:4)

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

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

答案 3 :(得分:1)

在这种情况下,管道将是性能最高的选项。

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);
  }
}

模板:

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