Styling Angular Elements
Provide examples of how to style Angular Elements using encapsulated styles and how to allow external styles to influence the element.
//Component Decorator specifying encapsulated CSS styles
@Component({
selector: 'app-custom-element',
template: `<div class="encapsulated-element">Styled Content</div>`,
styles: [
`.encapsulated-element {
color: blue;
background-color: lightgray;
}`
],
encapsulation: ViewEncapsulation.Emulated
})
export class CustomElementComponent {}
This code defines an Angular component with a template containing a div element. It includes encapsulated styles for the element, making those styles specific to this component only.
//Component Decorator using :host with ::ng-deep to style children with external styles
@Component({
selector: 'app-custom-element',
template: `<ng-content></ng-content>`,
styles: [
`:host ::ng-deep .external-class {
color: red;
}`
]
})
export class CustomElementComponent {}
In this component, the ::ng-deep combinator is used to allow external styles to penetrate the shadow DOM and style any child elements with the class 'external-class'.
//Component Decorator without encapsulated styles to allow global styles
@Component({
selector: 'app-custom-element',
template: `<div class="global-style-element">Styled Content</div>`,
styles: [],
encapsulation: ViewEncapsulation.None
})
export class CustomElementComponent {}
This code snippet creates an Angular component that does not encapsulate its styles. Thus, global stylesheet rules can affect the styling of elements within the component.