ngClass in host property of component decorator does not work

后端 未结 3 1229
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-07 17:44

I created the following simple example component that adds some attributes and listener to the component DOM element using the host property of the @Component decorator. In my c

相关标签:
3条回答
  • 2021-02-07 18:08

    ngClass is a directive and can't be used in host bindings. Host bindings only supports

    • property '[propName]':'expr'
    • attribute '[attr.attrName]':'expr'
    • event (event)="someFunction(event);otherExpr",
    • style [style.width]="booleanExpr"
    • class [class.className]="booleanExpr" binding.
    • class [class]="expr" where expr is a string with space separated classes
    0 讨论(0)
  • 2021-02-07 18:25

    This works for me and it's pretty modular:

    import { Component, HostBinding, Input } from '@angular/core'
    
    type Directions = 'vertical' | 'horizontal'
    
    /**
     * A hairline.
     */
    @Component({
      selector: 'hairline',
      styleUrls: ['./hairline.component.scss'],
      template: '',
    })
    export class HairlineComponent {
      @Input() direction: Directions = 'horizontal'
      @Input() padding = false
    
      @HostBinding('class')
      get classes(): Record<string, boolean> {
        return {
          [this.direction]: true,
          padding: this.padding,
        }
      }
    }
    
    
    0 讨论(0)
  • 2021-02-07 18:28

    Here are two different ways to bind a host element class to a property using the @HostBinding decorator:

    @HostBinding('class.enabled') private get isEnabled() { // use getter to reflect external value
        return this.selectionService.state.isEnabled;
    }
    
    @HostBinding('class.selected') private isSelected = false; // setting this add/removes 'selected' class
    
    constructor(private selectionService: SelectionService) {
        this.selectionService.select$.subscribe(isSelected => {
            this.isSelected = isSelected;
        });
    }
    
    0 讨论(0)
提交回复
热议问题