I have created a custom form control (using ControlValueAccessor) for input element, having following code for the writeValue method.
@ViewChild('inputElement', {static: true}) input;
writeValue(obj: any): void {
this.renderer.setAttribute(this.input.nativeElement, 'value', obj);
}
This method updates the view (input element) only once, that is when I initialize the form. If I manually patch the value of the form control associates with the above component, the form control gets updated, but the view doesn't get updated.
But, If I use the setProperty method instead of the setAttribute method, as follows,
@ViewChild('inputElement', {static: true}) input;
writeValue(obj: any): void {
this.renderer.setProperty(this.input.nativeElement, 'value', obj);
}
The view gets updated.
But the problem is, documents says that value is an attribute in HTML, not a dom property.
Can someone explain what is the difference between an attribute and a property in HTML which makes such behaviour in Renderer2 of Angular?
There is an attribute as well as a property called value, for an input element in HTML.
So, in HTML, attributes are defined on HTML elements and are supposed to be the initial values passed to them at the time of creating those elements. Once the browser creates the DOM (a.k.a. after rendering the page), the HTML elements become objects (node objects) and hence, they have properties.
Therefore, in order to change the current value of the input element using Renderer2 of angular, you need to use the setProperty method.
If you use, the setAttribute method, it will change the value only once, that is when you are creating the element. It will not change the current value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With