Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

449
Vistas
@HostBinding with a variable class in Angular

I have this code which sets a class on the host:

@HostBinding('class.fixed') true;

What I would like to do is make this a variable class that I can modify. How can I do this?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

This can't be made variable.

What you can do instead is to bind to the class property directly

@HostBinding('class') classes = 'class1 class2 class3';
over 4 years ago · Santiago Trujillo Denunciar

0

If you have a limited number of classes you can conditionally add each one:

@HostBinding('class.c1') get c1 () { return this.useC1; } 
@HostBinding('class.c2') get c2 () { return this.useC2; }

Note that .c1 and .c2 need to be defined outside the component.

Plunker

over 4 years ago · Santiago Trujillo Denunciar

0

I have to contradict the other answers, there is not a reason why binding class.foo shouldn't work. Actually, the following format works properly:

@HostBinding('class.foo') variableName = true;

If it doesn't work in your case, you might need to add a scope to your CSS class (you can see a discussion here).

The problem is that HostBinding only sees the host scope, it means that it only sees the classes and the id applied to the component itself, not to its children. So when you write your CSS, you need to specify that CSS belongs to the component itself (the host pseudoelement).

According to Angular documentation:

Use the :host pseudo-class selector to target styles in the element that hosts the component (as opposed to targeting elements inside the component's template).

You can easily specify the host scope just adding :host before your CSS rule:

:host.foo { // It only matches <Component class="foo">
  /* Your CSS here */
}

In place of

.foo { // It matches any <element class="foo" /> inside <Component>
  /* Your CSS here */
}

If you want, I created a working Plunker that you can see clicking here

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda