As per my understanding In Angular through Square brackets(input property binding) we set DOM properties of an HTML element.
Here, in the below example this is a valid way of changing font-size through input property binding in Angular.
<p [style.fontSize.px]="500" id="targeted">first-component works!</p>
But, this style.fontSize.px
doesn’t seems to be a valid DOM property because something like this won’t work in JS.
document.getElementById("targeted").style.fontSize.px = '50'
So, then how font-size can change through this in Angular <p [style.fontSize.px]="500" id="targeted">first-component works!</p>
if this style.fontSize.px
is not a valid DOM property?
And can I get an explanation on how this style.fontSize.px
can work in Angular?
2
Answers
Angular templates is a form of an extended HMTL that would be rendered to regular HTML, as the documentation describes it:
So in your example (https://stackblitz.com/edit/angular-qugq1z?file=src%2Fmain.ts):
This template with its style binding would be rendered to a valid "browser-friendly" HTML/CSS codes:
TL;DR answering your question:
It’s because you use the Angular’s binding syntax (square brackets) that handles the input value
[style.fontSize.px]="500"
and turns it into valid HTML attributes & CSS propertiesstyle="font-size: 500px;"
About the square brackets
That’s not completely correct. The square brackets mean using a directive. Things in square brackets are (almost) never just HTML attributes and they will be handled by the directive’s handler. Don’t be confused. The fact that directives use the same names as known HTML attributes doesn’t mean these attributes will be used in the result DOM as they are. The result value always depends on the directive’s logic.
That’s why you should look for the answer to your question somewhere in the Angular directives. And start from the binding syntax:
https://angular.io/guide/binding-syntax#binding-types-and-targets
How it works
You can learn the sources of the ngStyle directive that works similarly to
[style]
with only one difference:[ngStyle]
supports only object literal syntax and it cannot support strings or single values like[style]
does. Here you can see how the directive turns the input expressionstyle.fontSize.px
into valid HTML attributes.If you want to really dig into the sources of the [style] directive, you have to learn this lib @angular/animations which is here