[英]Angular 2 concatenate variable in interpolation
I have two related objects: 我有两个相关的对象:
itemsObj = {
'item1' : 'A1',
'item2' : 'A2',
'item3' : 'B',
'item4' : 'C',
'item5' : 'D'
};
And: 和:
itemsObj2 = {
'A1' : 'Very conservative and up',
'A2' : 'Conservative and up',
'B' : 'Balanced and up',
'C' : 'Growth and up',
'D' : 'Aggressive'
};
Interpolating {{itemsObj.item1}}
will return A1
and {{itemsObj2.A1}}
will return Very conservative and up
. 内插
{{itemsObj.item1}}
将返回A1
而{{itemsObj2.A1}}
将返回Very conservative and up
。
How to concatenate itemsObj.item1
with itemsObj2.A1
to return Very conservative and up
? 如何将
itemsObj.item1
与itemsObj2.A1
连接itemsObj.item1
返回Very conservative and up
?
My attempt: 我的尝试:
{{itemsObj2.itemsObj.item1}}
but of course this is wrong. {{itemsObj2.itemsObj.item1}}
但是这当然是错误的。 So may I know how to concatenate in my case? 那么我可以知道如何串联吗?
Do this: 做这个:
itemsObj2[itemsObj.item1] //setting itemsObj.item1's value as itemsObj2's key
DEMO: 演示:
itemsObj = { 'item1' : 'A1', 'item2' : 'A2', 'item3' : 'B', 'item4' : 'C', 'item5' : 'D' }; itemsObj2 = { 'A1' : 'Very conservative and up', 'A2' : 'Conservative and up', 'B' : 'Balanced and up', 'C' : 'Growth and up', 'D' : 'Aggressive' }; console.log(itemsObj2[itemsObj.item1])
TS TS
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public items: string[];
constructor() {
const itemsObj = {
'item1': 'A1',
'item2': 'A2',
'item3': 'B',
'item4': 'C',
'item5': 'D'
};
const itemsObj2 = {
'A1': 'Very conservative and up',
'A2': 'Conservative and up',
'B': 'Balanced and up',
'C': 'Growth and up',
'D': 'Aggressive'
};
this.items = Object
.values(itemsObj)
.map(itemKey => itemsObj2[itemKey]);
}
}
HTML 的HTML
<div *ngFor="let item of items">
{{ item }}
</div>
Output: 输出:
Very conservative and up
Conservative and up
Balanced and up
Growth and up
Aggressive
Stackblitz demo: Stackblitz演示:
https://stackblitz.com/edit/angular-pbdfux?file=src%2Fapp%2Fapp.component.html https://stackblitz.com/edit/angular-pbdfux?file=src%2Fapp%2Fapp.component.html
Since you need to match the key , you can do 由于您需要匹配密钥,因此您可以
<h1> {{itemsObj2[itemsObj.item1]}}</h1>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.