The Issue
Have you styled a component but the browser ignored and rendered that incorrectly? Well, this is a common issue which typically occurs for Angular beginners. Perhaps that you don’t have any idea how to handle it.
To simulate the issue, let’s assume we’ve a component for progress bar:
@Component({
selector: 'progress-bar',
template: `
<div></div>
`,
styles: [`
div {
width: 75%;
height: 20px;
background-color: dodgerblue;
}
`]
})
export class ProgressBarComponent {}
Well, it’s reasonable we’d like to style the progress bar element. For instance, changing its width
and background-color
.
So, let’s append these styles on the host element (which is the progress-bar itself):
:host {
width: 400px;
background-color: lavender;
}
Unfortunately, it seems that the element isn’t affected by the styles. Notice its actual width:
What we’re going to do now is to fix this issue.
The Solution
The reason for this issue is concealed in the way a browser interprets the host element, which doesn’t know it’s an HTML element at all and so the browser sets the default display
value (inline) for the host element.
In order to solve – we should adjust display
to the defined styles. Because of the fact that we used width
, we’ll attach display: block
:
@Component({
selector: 'progress-bar',
template: `
<div></div>
`,
styles: [`
:host {
display: block;
width: 400px;
background-color: lavender;
}
div {
width: 75%;
height: 20px;
background-color: dodgerblue;
}
`]
})
export class ProgressBarComponent {}
Finally, we get an incredible progress bar:
We completed the mission.