Para que sirve HostBinding?
b183a24aa1834cef9770d438afdb2890 import { Component , HostBinding } from '@angular/core' ;
@ Component (
:host {
padding : 10 px ;
background-color : red ;
} :host {
display : block ;
padding : 10 px ;
background-color : red ;
transition : background-color 0.5 s ease ;
@ HostBinding ( 'class.blue' ) get blue ( ) {
return this.color === 1 ;
}
@ HostBinding ( 'class.red' ) get red ( ) {
return this.color === 2
Written by Pol Valle I am particularly drawn to developing applications that are not only functional but also visually appealing and easy to use. I accomplish this by implementing SOLID principles and clean architecture, and applying testing to ensure quality.
{
selector
:
'app-host-binding'
,
standalone
:
true
,
template
:
`
<button (click)="toggleColor()">Toggle Color</button>
<div>{{color}}</div>
`
,
styles
:
[
`
:host {
display: block;
width: 300px;
height: 300px;
transition: background-color 0.5s ease;
}
:host(.blue) { // el uso de host(.laClase) es algo que esta directamente relacionado con HostBinding, ya que es la forma de referenciar la case
background-color: blue;
}
:host(.red) {
background-color: red;
}
:host(.green) {
background-color: green;
}
`
]
}
)
export
class
HostBindingComponent
{
public
color
:
number
=
3
;
@
HostBinding
(
'class.blue'
)
get
blue
(
)
{
// "get blue" es para nombrar a la funcion, pero podria tener cualquier otro nombre y seguiria funcionando
return
this
.
color
===
1
;
}
@
HostBinding
(
'class.red'
)
get
red
(
)
{
return
this
.
color
===
2
;
// Se aplicará la clase blue cuando color sea 2
}
@
HostBinding
(
'class.green'
)
get
green
(
)
{
return
this
.
color
===
3
;
}
toggleColor
(
)
{
this
.
color
=
(
this
.
color
%
3
)
+
1
;
}
}
}
:
host
(
.
blue
)
{
background-color
:
#a2d5f2
;
}
:
host
(
.
red
)
{
background-color
:
#f5a3a3
;
}
:
host
(
.
green
)
{
background-color
:
#a2f5a2
;
}
;
}
@
HostBinding
(
'class.green'
)
get
green
(
)
{
return this.color ===
3
;
}
toggleColor
(
)
{
// Sirve para cambiar el valor de this.color
this.color =
(
this.color
%
3
)
+
1
;
}