Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

If we attempt code like this:

<td [colspan]="1 + 1">Column</td>

or this:

<td colspan="{{1 + 1}}">Column</td>

We soon find out that "colspan is not a known native attribute."

From the A2 docs we learn that:

the element does not have a colspan property. It has the "colspan" attribute, but interpolation and property binding can set only properties, not attributes.

We must instead do this:

<td [attr.colspan]="1 + 1">Column</td>

Which is fair enough.

Question:

My question is, why is colspan not an attribute of the DOM, and if it is missing, how can the browser possibly render tables, since the browser renders the DOM and not the HTML?

Also, if I open my Chrome inspector, and go to the properties tab, why can I see colspan as a property of the Element?

Why does the DOM exhibit this inconsistency?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
235 views
Welcome To Ask or Share your Answers For Others

1 Answer

**Similar example <label for=...>

Property and attribute aren't always 1:1. An often encountered example is the label tag

<label for="someId">

In Angular

<label [for]="someId"> 

fails with the same error and you'd need to bind like

<label attr.for="{{someId}}">

or

<label [attr.for]="someId">

but

<label [htmlFor]="someId">

would also work because in this case htmlFor is the property that is reflected to the DOM for attribute. See also https://developer.mozilla.org/de/docs/Web/API/HTMLLabelElement for the htmlFor property (in the Properties section)

See also What is the difference between attribute and property?

colSpan the actual property name

According to https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement colSpan is the property that is reflected to the colspan attribute therefore (uppercase S)

<td [colSpan]="1 + 1">Column</td>

See also https://plnkr.co/edit/BZelYOraELdprw5GMKPr?p=preview

works just fine.

Why does Angular bind to properties by default

Angular binds to the property by default for performance reasons. Binding to an attribute is expensive because attributes are reflected in the DOM and a change in the DOM can causes reevaluation of CSS styles that might match after the change, while properties are just a value in a JavaScript object that changed.
With attr. you opt in explicitely to the expensive behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...