DEV Community

Budi Irawan
Budi Irawan

Posted on

DOM Property vs HTML Attribute in Property Binding

To gain more understanding of how Angular property binding works, we need to know the differences between DOM Property and HTML attributes. Property binding is a way to display a value comes from component to template.

If we have this ordinary HTML,

<input type="text" value="name"></input>

and if we want to bind a property to that in Angular, we wrap value with square brackets [ and ] such as:

<input type="text" [value]="name"></input>

We have value and [value]. Regardless of the brackets, they look exactly the same but they are different things.

What you must know is

  1. In the first code, value is an HTML attribute. See HTML Input.
  2. In the second code, value in [value] is a DOM property. See HTMLInputElement.

So, what Angular does in property binding is always target DOM property, not HTML attribute.

Does HTML attribute always have 1:1 mapping with DOM property?

The answer is no.

  • Some of them have 1:1 mapping e.g value, name, type, id, src
  • Some of them have 1:1 mapping with different name e.g. tabindex vs tabIndex, rowspan vs rowSpan, colspan vs colSpan
  • Some exist only in HTML attribute e.g. role, aria
  • Some exist only in DOM property e.g. textContent

Custom Property

Angular allows us to have custom property either from directive or component.

<div [ngStyle]="{'font-size': fontSize}"></div>

ngStyle is a custom property comes from Angular directive. Others such as ngClass, ngIf and etc.

Example for a custom component:

<student-list [students]="students"></student-list>

students is a custom property from component named StudentList that we have below

student-list.component.ts


@Component({
  selector: 'student-list'
  ...
})
export class StudentList {
  @Input() students;
}

Angular read from @Input of that component so it'll recognize students property.

The default behavior of Angular in property binding will always look for

  1. Custom property from directive or component
  2. DOM property

If Angular couldn't find the property from those two, it will trigger an error, for example we are trying to specify unknown property initial like below:

<input type="text" value="name" [initial]="initialValue" />

Alt Text

Summary

Property binding in Angular always targets to DOM property instead of HTML attribute. In order to support custom property, Angular will look for custom property from directive or component then DOM property.

Top comments (0)