Skip to content

Need a way for a component to add CSS classes to host non-destructively #7289

Closed

Description

@jelbourn

Say a user wants to add margin around a component:

<cool-thing class="extra-margin"> ... 

But the component itself has need to set a dynamic CSS class to the host element:

@Component({
  ...
  host: { '[class]': 'myCustomStyle' }
})
class CoolThing {
  myCustomStyle: string = figureOutWhichClassToUse();
}

Doing this in the component will completely overwrite the class property, wiping away the user's classes.

In other situations, NgClass serves this purpose, but a component cannot apply a directive to its host element. Using the [class.whatever] syntax also doesn't solve this, as the whatever is the variable part.

Proposal

Each component can, conceptually, have two distinct class lists: one that is from the user and one that comes from the component itself. These could be resolved independently with Angular rendering the union. Any time the user uses ngClass or the [class.whatever] syntax, it should override whatever is set to "class".

cc @mhevery

Activity

  1. added
    feature
    on Feb 25, 2016
  2. added
    hotlist: components team
    on Mar 4, 2016
  3. wembernard commented on Mar 9, 2016

    @wembernard

    👍

  4. self-assigned this
    on Mar 18, 2016
  5. JustasKuizinas commented on Feb 27, 2017

    @JustasKuizinas

    Any updates on this?

  6. Swiftwork commented on Mar 30, 2017

    @Swiftwork

    Isn't this quite easily solved by:

    @HostBinding('class') @Input('class') classList: string = '';

    This will capture any previous classes that have been manually assigned to the components dom. However does not facilitate for ones set dynamically by e.g. directives.

  7. added
    area: core
    on May 23, 2017
  8. tsu1980 commented on Sep 20, 2017

    @tsu1980

    My workaround.

    constructor(private el: ElementRef, private renderer: Renderer) { }
    
    ngOnInit() {
      this.renderer.setElementClass(this.el.nativeElement, 'my-item-' + this.itemType, true);
    }
    
  9. xmeng1 commented on Oct 18, 2017

    @xmeng1

    Currently, I use 3 methods to add the class name for a component. I don't know whether they are good way to do it, but it works according to my test.

    1. use host: https://stackoverflow.com/a/35996292/2000468

    @component({
    host: {
    '[class]': 'm-grid__item' +
    ' m-grid__item--fluid''},
    })

    1. use HostBinding

    @HostBinding('class.m-grid__item') public bindStyle: boolean = true;
    @HostBinding('class.m-grid__item--fluid') public bindStyle2: boolean = true;

    1. add class name to the component selector directly https://stackoverflow.com/a/38472185/2000468
      @component({
      selector: 'app-test .m-grid__item.m-grid__item--fluid',
      })
  10. MartinMa commented on Nov 8, 2017

    @MartinMa
    Contributor

    @xmeng1 Thanks for your summary. Just a small correction for approach 1 to avoid confusion (for anyone who might read this).

    It has to be '[class]': (instead of ['class']:)! The quotes have to be on the outside.

  11. xmeng1 commented on Nov 8, 2017

    @xmeng1

    @MartinMa you are right, thanks!

  12. trotyl commented on Dec 16, 2017

    @trotyl
    Contributor

    I used a manually provided NgClass to achieve this like:

    const prefix = 'ant-btn'
    
    @Directive({
      selector: 'button[antBtn]',
      providers: [ NgClass ],
    })
    export class HelloComponent implements OnChanges  {
      @Input() color: string = 'default'
    
      private hostClasses: { [name: string]: boolean }
    
      constructor(@Self() private ngClass: NgClass) { }
    
      ngOnChanges(changes: SimpleChanges): void {
        this.hostClasses = {
          [`${prefix}`]: true,
          [`${prefix}-${this.color}`]: true,
        }
    
        this.updateHostClasses()
      }
    
      private updateHostClasses(): void {
        this.ngClass.ngClass = this.hostClasses
        this.ngClass.ngDoCheck()
      }
    }

    More details can be found in the StackOverflow answer.

  13. 10 remaining items

  14. greggbjensen commented on Jul 9, 2019

    @greggbjensen

    This worked well for me and was a simple solution:

    @HostBinding('class.header-logo') public additionalClass: boolean = true;
  15. jpcmf commented on Aug 21, 2019

    @jpcmf

    My solution:

    @HostBinding('class') classList = 'fixed-class';
    @Input() class: string;
    
    constructor() {
    }
    
    ngOnInit() {
       if (this.class) {
          this.classList += ' ' + this.class;
       }
    }
    

    usage:

    <my-component [class]="'custom-class'">
        my content
    </my-component>
    

    output:

    <my-component class="fixed-class custom-class">
        my content
    </my-component>
    

    All examples

    constructor() {
    }

    I've just add @HostBinding('class') classList = 'd-flex flex-column h-100'; to my app.component and it works. Thank you @faizalmy 😃

  16. etay2000 commented on Oct 8, 2019

    @etay2000

    Wow another common use case issue lingering since 2016. Perhaps my open source software expectations are too high?

  17. trotyl commented on Oct 9, 2019

    @trotyl
    Contributor

    @etay2000 It has already been fixed in Ivy for some time, just wan't brought back to view engine.

  18. etay2000 commented on Oct 9, 2019

    @etay2000

    Ok thanks, I appreciate the info.

  19. exequiel09 commented on Dec 20, 2019

    @exequiel09

    I'm having an issue with HostBinding in Angular v9.0.0-rc.6 which outputs the string [MAP].

    Screen Shot 2019-12-20 at 5 05 52 PM

    I am currently using @faizalmy reply here in this issue

    My solution:

    @HostBinding('class') classList = 'fixed-class';
    @Input() class: string;
    
    constructor() {
    }
    
    ngOnInit() {
       if (this.class) {
          this.classList += ' ' + this.class;
       }
    }
    

    usage:

    <my-component [class]="'custom-class'">
        my content
    </my-component>
    

    output:

    <my-component class="fixed-class custom-class">
        my content
    </my-component>
    

    /cc @kara @jelbourn

  20. vthinkxie commented on Jan 8, 2020

    @vthinkxie
    Contributor

    this issue has been fixed in angular 9.0.0

    anyone who meet this issue can try the below codes in angular 9

    import { Component } from "@angular/core";
    
    @Component({
      selector: "app-root",
      template: '<button (click)="updateHostClassList()">host</button>',
      host: {
        "[class]": "hostClass"
      }
    })
    export class AppComponent {
      hostClass = {};
      updateHostClassList() {
        const random = Math.floor(Math.random() * 1000).toString(36);
        this.hostClass = {
          [random]: true
        };
      }
    }
  21. PeterHewat commented on Jan 27, 2020

    @PeterHewat

    I confirm this works in Angular 9.0.0
    Here is a simple example:

    import { Component, OnInit, HostBinding } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: 'app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent implements OnInit {
    
      @HostBinding('class') private hostClass: object = {};
    
      public ngOnInit(): void {
        this.addClass('myYellowBackground');
      }
    
      private addClass(className: string): void {
        this.hostClass[className] = true;
      }
    
      private removeClass(className: string): void {
        delete this.hostClass[className];
      }
    
    }

    Then, if you add a class to that component as follows...

    <app-root class="myRedBorder"></app-root>

    ... both myRedBorder and myYellowBackground classes will be applied to the instance of <app-root/>

  22. wnvko commented on Feb 5, 2020

    @wnvko

    I think this is some easy way for adding class to component:

    @Component({
      ...
    })
    export class CoolThingComponent {
      @HostBinding('class.myCustomStyle') public hostClass = true;
    }
    

    And then use component like this:

    <cool-thing class="extra-margin">
    

    @vladimiry you can add ass much classes as you need like this:

    @Component({
      ...
    })
    export class CoolThingComponent {
      @HostBinding('class.myFirstHostedClass')
      @HostBinding('class.mySecondHostedClass')
      public hostClass = true;
    }
    

    and then several inline classes too:

    <cool-thing class="firstInlineClass secondInlineClass">
    
  23. vladimiry commented on Feb 5, 2020

    @vladimiry

    @wnvko adding one class is easy, the issue is about host-bind a multiple classes.

  24. mhevery commented on Feb 6, 2020

    @mhevery
    Contributor

    This has been resolved as of #34938 Closing the issue.

  25. angular-automatic-lock-bot commented on Mar 8, 2020

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  26. locked and limited conversation to collaborators on Mar 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: corefeaturehotlist: components teamstate: Needs Design

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions