Home > Software engineering >  Apply :host selector in Angular based on input
Apply :host selector in Angular based on input

Time:07-16

I have a component which accepts an input called size, it looks something like this;

<app-container [size]="level"></app-container>

level can be a series of strings, such as large, small and medium. I'd like to apply a :host selector within my components stylesheet so if a size input is provided it applies some CSS to it.

I can do this with CSS via the following if I use class, but I can't seem to do the same with Angulars input.

<app-container ></app-container>
:host(.large) {
  color: blue
}

Is such a thing possible?

CodePudding user response:

// not necessarily a getter, it could just be a variable
@HostBinding('class.large') public get isLarge() {
  return this.size === 'large';
}
:host {
  &.large {
    color: blue;
  }
}

CodePudding user response:

I don't think this is possible without some ugly hacks, but you can achieve similar functionality by wrapping the html in a div.

HTML:

<div [ngClass]="{'large': level === 'large'}">
  // Your HTML here
</div>

CSS:

.large {
  color: blue;
}

Edit: Here's the hacky answer if you want it. It only needs a change in the typescript.

class YourComponent {
  @Input() level: string;

  constructor(private el: ElementRef) {}

  ngOnInit() {
    if (this.level === 'large') {
      this.el.nativeElement.style.color = 'blue';
    }
  }
}

Here it is in action: https://stackblitz.com/edit/angular-ivy-lre3ur

  • Related