【问题标题】:Angular - Add dynamic class at existing classes on host componentAngular - 在主机组件上的现有类中添加动态类
【发布时间】:2020-10-07 16:08:14
【问题描述】:

我有这个组件,我需要在宿主组件中动态添加动态类

@Component({
 selector: 'test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss'],
 encapsulation: ViewEncapsulation.None
})

export class TestComponent implements OnInit {

  @HostBinding('className') componentClass: string;

  @Input() name: string;

  constructor() {}

  ngOnInit(): void {
   this.componentClass = this.name ? `test-icons test-icons-${this.name}` : '';
  }

}    

这可行,但如果我尝试在我的组件上添加一个类,则会被控制期间添加的类覆盖。

例如,如果我愿意:

 <test-component class="custom-class-i-added" [name]="'icon']></test-component>

class "custom-class-i-added" 消失了……我想创建一个系统,在现有的类中添加动态类……有没有办法?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    这应该完全符合您的要求:

    export class HelloComponent implements OnInit  {
      @Input() name: string;
      
      // Use input to combine class passed from parent with classes set in component.
      @HostBinding('class') @Input('class') classList: string = '';
    
      ngOnInit() {
        this.classList = `${this.classList} test-icons test-icons-${this.name}`;
      }
    }
    

    【讨论】:

      【解决方案2】:

      作为一种解决方法,您可以使用 @Attribute 装饰器获取组件类属性,然后与 componentClass 连接,如下所示:

      component.ts

      constructor(@Attribute('class') private hostClass: string){}
      
        ngOnInit(): void {
         this.componentClass = this.name ? `${this.hostClass} test-icons test-icons-${this.name}` : this.hostClass;
        }
      

      Working Example

      【讨论】:

        猜你喜欢
        • 2018-12-13
        • 1970-01-01
        • 2016-10-22
        • 1970-01-01
        • 1970-01-01
        • 2017-10-29
        • 1970-01-01
        • 2020-08-21
        • 2017-07-17
        相关资源
        最近更新 更多