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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43136846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:24:22  来源:igfitidea点击:

Angular2 check if object has peoperty inside *ngIf

angulartypescriptangular2-componentsangular-ng-if

提问by Pratap A.K

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?

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

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

回答by Sniper

You can do it simply in the html:

你可以简单地在 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>  

回答by Günter Z?chbauer

I guess this should do what you want:

我想这应该做你想做的:

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

回答by Bougarfaoui El houcine

in addition to what Günter Z?chbauersaid:

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

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