In my angular 5 app that I am working on I retrieve, from dynamodDB, a json that looks like something like this (it is retrived as an array and used with *ngFor
, but for the simplisity for this question I can say it is stored like this in the component":
public person = {
"userID" : "abc123...",
...
"period1_status" : "applied",
"period2_status" : "placed",
"period3_status" : "applied",
...
}
In my component I have a variable string, named chosenPeriod, which I can change with a <select>
tag. It is changed to 'period1'
, 'period2'
or 'period3'
.
public chosenPeriod = 'period2'
And in other parts in the html for the component I have a <mat-chip>
(using material2) which I only want to show if periodX_status
equals to 'applied'
, where X is the value of chosenPeriod
. Somthing like this:
<mat-chip *ngIf="person.chosenPeriod+'_status' == 'applied'"><mat-icon>drag_handle</mat-icon></mat-chip>
where I want it to be *ngIf="person.period1_status == 'applied'
if chosenPeriod = 'period1'
etc.
The example above doesn't of course work. But is there a way in angular5 / HTML to do this?
You can use object property accessors/bracket notation, as follows:
<mat-chip *ngIf="person[chosenPeriod + '_status'] == 'applied'">
In the example above, if chosenPeriod
was 'period1'
, it would be the same as:
<mat-chip *ngIf="person['period1' + '_status'] == 'applied'">
Which is the same as:
<mat-chip *ngIf="person['period1_status'] == 'applied'">
What, in the end, has the same effect of:
<mat-chip *ngIf="person.period1_status == 'applied'">