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>
Just for readability created library ngx-if-empty-or-has-items it will check if an object, set, map or array is not empty.
Using myObject. hasOwnProperty('prop') is a great way of accessing the Object's keys directly, which does not look into the Object's prototype - hooray, this is great for specific use cases. hasOwnProperty returns a Boolean for us on whether a property exists.
The *ngIf directive is most commonly used to conditionally show an inline template, as seen in the following example. The default else template is blank.
The * syntax means that ngIf is a structural directive, meaning that it affects the structure of the page.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With