Component CSS - name vs :host?

I’m building my first ionic (v3) application after spending some time with regular angular (v2 and v4), and am trying to wrap my head around the difference.

One thing that’s different is the way component styles get applied via either the inline scss or the external scss file. In angular, you use a :host {} selector, and with ionic, you use the component name. It seems like (at first try, at least) the :host selector doesn’t work at all. Angular normally converts those things into funky selectors that get added at runtime, like _nghost-c1 and stuff. My hypothesis is that this is because ionic doesn’t use the angular component router.

I don’t particularly have a horse in this race, it’s more just that this is an inconsistency between the two frameworks that doesn’t make a lot of sense from the outside. Is there a convenient way to enable :host selectors in ionic? I’d love to use them, since it’d make the copypasta porting of an ng4 app into ionic that much simpler.

2 Likes

Answering my own question here:

it looks like I can set @Component({ styles: [``]}) as usual and the angular css isolation stuff will work just fine. The default component.scss that the cli generates gets imported into the generated css, but you can ignore that if you want. It looks like you can’t do styleUrls: string[] in the Component definition the way you would with a vanilla ng4 setup - the system fails at runtime looking for the relevant file.

This still feels like an unnecessary inconsistency - I imagine this is for historical reasons, as the ionic cli more-or-less predates the angular one (at least as I remember it, from having played with yeoman, broccoli, gulp, and all that stuff a few years back, and watching the ember-cli and ionic projects proceed).

2 Likes

Hmm, strike that - the style content you put in there isn’t parsed as scss, which is kind of a bummer. I imagine this is a webpack thing. I’ll dig a bit, but this is probably more trouble than it is worth.

Just a shot in the dark, but did you ever get :host working in Ionic? I’m porting a ng2 over to Ionic and there are quite a bit of components that will need to get this updated and being able to use host like in ng2 would be great to access that components root element.

The way I’ve been able to do is move the host CSSdefinition up to the parent components CSS file with a class name and that works. It’s just a bit of a disconnect and not keeping that component CSS together in its own files.