Reputation: 2371
I'm trying to update the value of an input that isn't bound to a <form>
in my component, and my research has lead me to use the Renderer2
service that Angular provides.
So I have my input that looks like this:
<input type="text" #zipEl placeholder="Enter zip">
<button type="button" (click)="getLocation()">
<span>Use current location</span>
</button>
And in my component, I'm trying to just set the value simply like this:
@ViewChild('zipEl') zipEl:ElementRef;
constructor(private renderer: Renderer2) {
}
getLocation() {
this.renderer.setValue(this.zipEl, '94085');
}
Though nothing is happening. When I click the button to run the function, the input box never gets its value updated with 94085
. Does anyone know what I'm doing wrong here?
Thanks in advance!
Upvotes: 6
Views: 9044
Reputation: 2822
I believe you need to use setProperty
:
getLocation() {
this.renderer.setProperty(this.zipEl.nativeElement, 'value', '94085');
}
Upvotes: 23
Reputation: 431
You can try it like this:
constructor(element: ElementRef, renderer: Renderer2) {
const input = renderer.createElement('input');
renderer.setAttribute(input, 'value', '94085');
renderer.listen(input, 'keyup', (ev) => {
console.log(ev);
});
renderer.appendChild(element.nativeElement, input);
}
Upvotes: 0
Reputation: 2371
Using Angular v4.0.2, I ended up using the .setAttribute()
function shown here:
getLocation() {
this.renderer.setAttribute(this.zipEl, 'value', '94085');
}
Upvotes: 1
Reputation: 11
What is your angular version ?
I do not yet find in which version is Renderer2
But it work with Renderer :
@ViewChild('zipEl') zipEl:ElementRef;
constructor(public renderer: Renderer) {
}
getLocation() {
this.renderer.setElementAttribute(this.zipEl.nativeElement, 'value', '94085');
}
Upvotes: 0