使用占位符&动态生成输入元素ngModel [英] Generate input element dynamically with placeholder & ngModel
问题描述
我想以角度2+动态生成输入元素.我有如下所示的占位符标题数组和值数组:
I want to generate inputs elements dynamically in angular 2+. I've placeholder title array and value arrays as below:
在我的组件中,有两个如下图所示,其中两个键都相同,将值映射到title:
In my component I have two map as below where key is same for both which maps the value to title:
const placeholderMap = {fullName: 'Name', value: 'Product Value'};
cont valueMap = {fullName: 'Alpha Product', value: '2234.234'};
我想使用上面的地图并动态生成如下的输入元素:
I want to use the map above and generate inputs elements like below dynamically:
<input matInput placeholder="Name" value='Alpha Product'/>
<input matInput placeholder="Product Value" value='2234.234'/>
推荐答案
您可以使用 * ngFor
包含键名数组,以循环浏览并绑定地图中的所有值.
You can us an *ngFor
with an array of the key names to loop through and bind all of the values in your map.
<input matInput *ngFor="let key of ['fullName', 'value']"
[placeholder]="placeholderMap[key]"
[(ngModel)]="valueMap[key]" />
除了可以在模板中显式指定所有键名之外,您还可以像这样对组件中的所有键进行引用:
Instead of specifying all the key names explicitly in the template you could also get a reference to all the keys in your component like so:
ngOnInit() {
this.inputKeys = Object.keys(this.valueMap);
}
这篇关于使用占位符&动态生成输入元素ngModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!