Doplax.Dev
  • Home
  • About me
  • Blog
  • Work Experience
  • Contact
  • Home
  • About me
  • Blog
  • Work Experience
  • Contact

Got a project in mind or just want to say hi?

Get in touch

© 2026 Doplax.Dev — All rights reserved.

December 21, 2023

Para que sirve HostBinding?

  • Angular

b183a24aa1834cef9770d438afdb2890


import { Component, HostBinding } from '@angular/core';

@Component({
  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{
        padding: 10px;
        background-color: red;
      }

:host {
        display: block;
        padding: 10px;
        background-color: red;
        
        transition: background-color 0.5s ease;
      }
      :host(.blue) {
        background-color: #a2d5f2;
      }
      :host(.red) {
        background-color: #f5a3a3;
      }
      :host(.green) {
        background-color: #a2f5a2;
      }



@HostBinding('class.blue') get blue() {
    return this.color === 1;
  }

  @HostBinding('class.red') get red() {
    return this.color === 2;
  }

  @HostBinding('class.green') get green() {
    return this.color === 3;
  }

  toggleColor() { // Sirve para cambiar el valor de this.color
    this.color = (this.color % 3) + 1;
  }




min 5






















PreviousSimplify Your Imports in JavaScript with Module AliasesNextDiferencia entre interfaz y type en TS

Related posts

  • Data Binding en Angular: qué es, tipos y cómo funciona realmenteAngular
  • Comandos para la creación de módulos en AngularAngular
  • Como instalar eslint en AngularAngular
  • Como usar iconos de FontAwesome en AngularAngular

Written by Pol Valle

Written by Pol Valle

I'm particularly drawn to building apps that are not only functional but also visually appealing and easy to use. I do it by applying SOLID principles, clean architecture and testing to ensure quality.