簡體   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