Reputation: 85
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?
Upvotes: 1
Views: 757
Reputation: 2418
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}`;
}
}
Upvotes: 2
Reputation: 27363
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;
}
Upvotes: 0