Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 418
Archimede Avatar asked Oct 28 '25 10:10

Archimede


2 Answers

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.

like image 70
ararb78 Avatar answered Oct 31 '25 00:10

ararb78


The :host() CSS pseudo-class function selects the shadow host of the shadow DOM containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host.

Ref:https://developer.mozilla.org/en-US/docs/Web/CSS/:host()

Try this it will work

component.css

:host(.alfa){
  color: red;
}
like image 41
Chellappan வ Avatar answered Oct 31 '25 01:10

Chellappan வ