It seems like using direct attributes and the ng-attr-*
directive do the same thing. For example, the following render equivalently:
<div ng-attr-id="{{ 'object-' + value }}">ID</div>
<div id="{{ 'object-' + value }}">ID</div>
When should I use ng-attr-*
and when should I use the direct HTML attribute?
ng-attr is used for add or not the attribute in context. If the expression {{undefined || null}} , the attribute is not added otherwise if has a value then attribute is added with the value {{ value }} . The most common cases is in interpolation.
We simply use attribute binding to add and set a value for a data attribute. According to Angular docs: Attribute binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix attr, followed by a dot (.)
String Interpolation in Angular 8 is a one-way data-binding technique that is used to transfer the data from a TypeScript code to an HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view.
ng-attr is used for add or not the attribute in context. If the expression {{undefined || null}}
, the attribute is not added otherwise if has a value then attribute is added with the value {{ value }}
.
The most common cases is in interpolation.
Related:
Conditionally adding data-attribute in Angular directive template
You use them for custom html data attributes - like if you wanted an attribute of let's say myData you would do
<div ng-attr-myData="{{ 'object-' + value }}">ID</div>
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