I'm new to Angular, and I am reading the ng-book and I found this code :
import {
Component,
Input,
HostBinding
} from '@angular/core';
import { Product } from '../product.model';
/**
* @ProductRow: A component for the view of single Product
*/
@Component({
selector: 'product-row',
templateUrl: './product-row.component.html',
})
export class ProductRowComponent {
@Input() product: Product;
@HostBinding('attr.class') cssClass = 'item';
}
I don't understand why we use this line here
@HostBinding('attr.class') cssClass = 'item';
I searched some posts here and people say that it "will bind the property to the host element, If a binding changes, HostBinding will update the host element".
But I checked the template file but I didn't find anything called "cssClass" or "item" inside :
<product-image [product]="product"></product-image>
<div >
<div >{{ product.name }}</div>
<div >
<div >SKU #{{ product.sku }}</div>
</div>
<div >
<product-department [product]="product"></product-department>
</div>
</div>
<price-display [price]="product.price"></price-display>
CodePudding user response:
When angular render product-row
it, you will see in DOM class in that element. In your case it will be item
So if you change cssClass
to any value it will be automatically updated in DOM.
You can also do data attributes @HostBinding('attr.data-id')
or @HostBinding('style.background') backgroundColor = 'red';
Its really handy as lets say you can add logic where you pass input parameter to your row, then based on that index lets say you assign your cssClass
to be item-odd
or item-even
this way you can use some css to style your components