My question is what is the difference between this three methods:
[id]="item.id"
[attr.id]="item.id
id={{item.id}}
Which method is the best?
CodePudding user response:
Both [id]="item.id" and id="{{item.id}}" will output the same result since both are ways to bind a variable to the template. [] is using binding sintax and {{}} iterpolation. Both uses are OK as far as i know and it is up to your preference.
On the other hand [attr.id]="id" might get you a different result. This will put the value of the variable id to the attribute ID of the html. e.g: if variable id=1234.
<div [attr.id]="id"></div> => <div id="1234"></div>
But if you have a component with an input named "id" such as:
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello-world',
template: `<h1>Hello your ID is: {{id}}</h1>`,
styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
@Input() id: string;
}
Using [attr.id] is not the same as using [id].
- [id] will populate the input variable of the component named "id"
- [attr.id] will define the HTML attribute "id"
Hope this helps solve your question.
CodePudding user response:
You will need to know the difference between attributes and properties
The first is property binding, which is commonly used in binding to dynamic HTML properties. Its correct use case is that first example [id]="item.id"
, in which the HTML property is ID
The third is text interpolation, commonly used to "incorporate dynamic string values into your HTML templates". The correct use case should be <p>Audi has sold {{totalCarsSold}} cars in 2021</p>
, where totalCarsSold
is defined in your component. Even though the third works as well, it is not recommended in binding HTML properties.
The second one, however, is attribute binding. Since angular uses property bindings, it cannot 'understand' the role of that attribute that has been bound as a property. The prefix .attr
must therefore be used to tell angular that that is an attribute being used. For example, in a case of a dynamic progress bar below,
<div style="width: {{progress}}%" [attr.aria-valuenow]="progress"> {{progress}}% </div>
since aria is an attribute, it must be prefixed with the .attr
, or else angular throws an error Can't bind to 'aria-valuenow' since it isn't a known property of 'div'
Be sure to check the above links for detailed use cases, or this answer on stackoverflow on the same