angularangular2-hostbinding

Angular @HostBinding, simple example and fundamentals


I would understand very well the Angular @HostBinding concept. Unfortunately, my book is very good but this concept is not very clearly explained.

See please the code:

@Component({
  selector: 'app-test-component',
  templateUrl: './test-component.component.html',
  styleUrls: ['./test-component.component.css']
})
export class TestComponentComponent implements OnInit {

  @Input() dataModel:AppModel;
  @HostBinding('attr.class') cssClass = 'alfa';

  constructor() { 

(...)

My personal explanation: "host binding allow to set something in the host element (in this case the app-test-component tag) from within the component it self (in other words, from this file I mentioned below); in this case, I set the class attribute of this tag to the variable named cssClass and with attribute 'alfa'". Is it correct?

In this case, if I defined the 'alfa' style in the correspondent css file, why I don't see this style (i.e. background color or something else) in the page which shows my component?

Edit

I need to understand very well the row

@HostBinding('attr.class') cssClass = 'alfa';

Is this exactly equivalent to "set the class attribute of the template element to the string cssClass assigned to value 'alfa'"? (or, in other words, is the same as the instruction "class='alfa'" in the main template tag)

And, can you please write me also an example with the same result but without the using of @hostbinding? I am sure that seeing these equivalent solutions in comparison can be very helpful for me.


Solution

  • In Angular, the @HostBinding() function decorator allows you to set the properties of the host element from the directive class.

    Let's say you want to change the style properties such as height, width, color, margin, border, etc., or any other internal properties of the host element in the directive class. Here, you'd need to use the @HostBinding() decorator function to access these properties on the host element and assign a value to it in directive class.

    The @HostBinding() decorator takes one parameter, the name of the host element property which value we want to assign in the directive.