Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between an Attribute and a Property in HTML?

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?

like image 547
Dulanjaya Tennekoon Avatar asked Jul 26 '19 04:07

Dulanjaya Tennekoon


Video Answer


1 Answers

There is an attribute as well as a property called value, for an input element in HTML.

  1. Value Property - Represents the current value of the input element.
  2. Value Attribute - Represents the initial value of the input element.

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.

like image 92
Dulanjaya Tennekoon Avatar answered Sep 30 '22 13:09

Dulanjaya Tennekoon