简体   繁体   中英

Apply class conditionally to component host

I'm trying to apply a class to the component tag only if something is true.

How I could turn this host into a conditional host so that I will apply the desired class when needed?

@Component({
  selector: 'k-sidebar',
  host: {
   class: '{{isChanged}}'
 },
 templateUrl: './ng-k-side-bar.component.html',
 encapsulation: ViewEncapsulation.None

})

You can set the host element class conditionally with @HostBinding :

condition: boolean = true;

@HostBinding("class") private get hostClass(): string {
  return this.condition ? "redBorder" : "";
}

or for a specific class name (eg redBorder ):

@HostBinding("class.redBorder") private get hasRedBorder(): boolean {
  return this.condition;
}

See these two demos: stackblitz 1 , stackblitz 2 .

if 'my-class' is a class name you setup it like this

@Component({
  selector: 'k-sidebar',
  host: {
   '[class.my-class]': 'isChanged'
 },
 templateUrl: './ng-k-side-bar.component.html',
 encapsulation: ViewEncapsulation.None
})
export class MyComponent {
  isChanged = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM