1

I have this component and I need to add dynamic class at host component dynamically

@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}` : '';
  }

}    

this works but if I try to add one class on my component this is override by the classes added during control.

Example, if I wtite:

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

class "custom-class-i-added" disappear...i want to create a system that add dynamic classes at the existing ones....Is there a way?

2 Answers 2

2

This should do exactly what you want:

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}`;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

As a workaround You can use @Attribute decorator to get component class attribute and then concate with componentClass something like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.