Home > database >  How to access dynamic conditional nested object properties in an angular template?
How to access dynamic conditional nested object properties in an angular template?

Time:01-06

I'm trying to check something like this: *ngIf="charts.data['key with space']?[dynamicKey] !== undefined"

But the compiler then appears to see this like a ternary operator..

Another option is to write it like this, but thats way longer and becomes more unreadable in longer property chains:

*ngIf="charts.data['key with space'] && charts.data['key with space'][dynamicKey] !== undefined"

CodePudding user response:

Why not just create a method in your class to do the evaluation and then return that to the template?

*ngIf="doesExist(charts.data['key with space'], dynamicKey)"

Function:

doesExist(obj: any, key: string): boolean {
  return obj.hasOwnProperty(key)
}

Not tested, but gives you the idea...

CodePudding user response:

I would create a function and return a boolean and therefore remove the logic from the html entirely.

*ngIf="canShowItem(key, dynamicKey)"

canShowItem(key: string, dynamicKey: string): boolean {
 const data = charts.data[key];
 if(!data) { return false};
 return data[dynamicKey] !== undefined
}
  • Related