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 { Componen
I've just solved it using this
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);
}
}
Thanks for all @nikolaus and @gab
If you want to dynamically change the attributes of a single <input>
tag, I would recommend you use @ViewChild
. For example,
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
}
}
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