angular style not applied on components (despite the use of host selectors)

About the width issue your facing in the test component, assuming you want the whole element to span to a width of 350px, you should define its display property to block:

:host {
  background: blue;
  display: block;
}

Custom elements does not have a default display property and your browser can't guess what your means are.

About applying the .test style on your component, the app-component styles are encapsulated using the _nghost-c0 and _ng-content-c0 attributes and therefor not being applied on test.component. If you want to apply the .test on other components you can either write the CSS RULE on the global styles.css file which is applied globally:

//styles.css
.test {
  background-color: red;
  width: 350px;
}

or use the viewEncapsulation property on your @component decorator like this:

//app.component.ts
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None
})

and then you can leave the CSS RULE on the app.component file

//app.component.css
.test {
  background-color: red;
  width: 350px;
}

but now the styles in that file are not encapsulated and will penetrate other components.


Its because custom components (custom html tags) are rendered as inline elements.

use

:host
{
  background-color: blue;
  display: block;
}

And it will work.

https://stackblitz.com/edit/angular-hknw2a?file=src/app/app.component.scss

Tags:

Angular