Juri Strumpflohner

Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, occasionally speaks at conferences and holds training workshops.

The good old “ngClass”

Straight away, there’s still the good old NgClass which might especially be known by Angular 1 developers. NgClass allows to pass in an object (key:value) where the key represents the class and the value a boolean condition which controls whether that specific class is applied to the element or not.
That said, it is the preferred way of adding one or more classes to an element.

It is made available under the @angular/common module which is imported already for you (under the @angular/browser module), so there’s no need to do it manually. Then we can use it just as we did in Angular 1. Here’s the full code example.

Adding a single class

An alternative to the ngClass and especially in situations when only a single class needs to be applied is the following syntax.
Similarly as we did with the background-color above, we can add a single class, using the following notation: [class.nameOfClass]="someCondition".

Using :host(..) and @HostBinding

Consider you have a component <styled> which you’d like have different CSS classes applied based on some setting, like .yellow-style in case when you specify <styled style="yellow"> and .red-style when you pass in red: <styled style="red">.

What’s important to note here is that, different to what we did so far, we don’t want the CSS class to be applied on some element that’s internal to our component, but onto the component itself. Example:

As you can see, we use the special :host(...) selector to target the styles on the element that hosts the component. More info on the official docs about this. In this way .yellow-style as well as .red-style will be visible at the host component level while they’d be otherwise encapsulated and only applicable to elements within our StyledComponent.

Next, we define an @Input() property which allows us pass in the style configuration.

@Component({...})exportclassStyledComponent{@Input()style;}

What we’re still missing is to programmatically set the CSS class on our host element based on the value of the style input property. We use the @HostBinding for this:

The important part here is the ElementRef and the Renderer which I import in the constructor.

The ElementRef allows us to gain access to the nativeElement API via

el.nativeElement.style.backgroundColor='yellow';

This way you can deliberately modify the properties of the native DOM element. So why would I want to use the Renderer. Well, Angular isn’t only build for the browser, but it can potentially also be rendered on the server or render native elements on a mobile device (via NativeScript for instance). Thus, the Renderer provides an abstraction over the native elements.