繁体   English   中英

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

[英]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;
}

我的变量类型如下

selectedElement: Element;

现在在 html 中如何检查对象是否具有属性“类型”?

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

我想这应该做你想做的:

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

您可以简单地在 html 中完成:

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

或者

<div *ngIf="selectedElement.hasOwnProperty('type');then 
showMyDiv">...</div>

<ng-template #showMyDiv> 
my div
</ng-template>  

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

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

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

:

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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