Angular 5插入动态输入属性 [英] Angular 5 Insert dynamic input attributes
问题描述
我想向输入的html标签动态插入属性,但是我不知道要这样做:
I want to insert dynamically attributes to an input html tag, but I don't know to to do this:
我从组件方面获得了这段代码:
I've got this code from component side:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-transclusion',
templateUrl: './transclusion.component.html',
styleUrls: ['./transclusion.component.css']
})
export class TransclusionComponent implements OnInit {
elements: any;
constructor() { }
ngOnInit() {
this.elements = {};
this.elements.name = 'TEST1';
this.elements.type = 'text';
this.elements.value = '12';
this.elements.placeholder = 'PRUEBA';
this.elements.maxlength = '10';
// This is only for test elements keys
for (const el in this.elements) {
if (this.elements.hasOwnProperty(el)) {
console.log(`${el}: ${this.elements[el]}`);
}
}
}
}
这是我的模板面:
<input type="text"
[attr.name]="elements.name"
[attr.value]="elements.value"
[attr.placeholder]="elements.placeholder"
[attr.maxlength]="elements.maxlength"/>
我希望任何类似于"forin"的方法都可以遍历每个elements属性并在输入标签上动态插入,因此结果如下:
I want any 'forin' like method to iterate over each elements attribute and insert dynamically on the input tag, so it results like this:
<input type="text"
[attr.*for="el in elements"]="el"/>
我该如何实现?
最好的问候 安东尼奥
推荐答案
如果要使用属性配置"输入字段,则使用错误的方法,应使用渲染器服务随角度一起提供
You are following the wrong approach if you want to use attributes to "config" your input field you should use directives instad of a component...
and if you need to modify the native element on which you are appling your directive use the renderer service shipped with angular
这篇关于Angular 5插入动态输入属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!