我想将属性动态地插入到一个输入html标签中,但我不知道该怎么做:
我从组件端得到了这段代码:
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‘类方法迭代每个元素属性,并在input标记上动态插入,因此它的结果如下:
<input type="text"
[attr.*for="el in elements"]="el"/>我如何实现这一点?
向安东尼奥致以最美好的问候
发布于 2018-01-28 04:07:55
如果你想使用属性来“配置”你的输入域,你应该使用directives instad of a component...
如果需要修改在其上应用指令的原生元素,请使用angular附带的renderer service
发布于 2018-01-28 06:28:04
我刚刚用这个解决了这个问题
import { Component, Renderer2, ElementRef, OnInit } from '@angular/core';
@Component({
selector: 'app-transclusion',
templateUrl: './transclusion.component.html',
styleUrls: ['./transclusion.component.css']
})
export class TransclusionComponent implements OnInit {
elements: any;
constructor(private renderer: Renderer2, private el: ElementRef) { }
ngOnInit() {
this.elements = {};
this.elements.name = 'TEST1';
this.elements.type = 'text';
this.elements.value = '12';
this.elements.placeholder = 'PRUEBA';
this.elements.maxlength = '10';
const div = this.renderer.createElement('input');
for (const el in this.elements) {
if (this.elements.hasOwnProperty(el)) {
this.renderer.setAttribute(div, el, this.elements[el]);
}
}
this.renderer.appendChild(this.el.nativeElement, div);
}
}感谢所有的@nikolaus和@gab
发布于 2018-01-28 03:58:39
如果您想要动态更改单个<input>标记的属性,我建议您使用@ViewChild。例如,
import { Component, AfterViewInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-transclusion',
template: `
<input #foobar/>
`,
styleUrls: ['./transclusion.component.css']
})
export class TransclusionComponent implements AfterViewInit {
@ViewChild('foobar') foobar: ElementRef;
constructor() { }
ngAfterViewInit() {
this.foobar.nativeElement.value = 'foobar';
// change other values of element
}
}https://stackoverflow.com/questions/48479875
复制相似问题