Component Style Encapsulation and CSS Best Practices
Demonstrate how to use Angular's style encapsulation along with best CSS practices for maintainable styling.
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css'],
// Use encapsulation property to define the style encapsulation strategy
encapsulation: ViewEncapsulation.Emulated // This is the default and emulates Shadow DOM
})
export class ExampleComponent {
// Component logic goes here
}
This code snippet is an Angular component with encapsulated CSS. The styles defined in 'example.component.css' will only apply to 'app-example' and won't affect other components due to Angular's style encapsulation.
/* example.component.css */
/* Use BEM naming convention for class names */
.example__element {
/* Base styles for the element */
}
.example__element--modifier {
/* Modification based on a different state or variation */
}
This CSS snippet follows BEM (Block Element Modifier) naming convention, which helps in maintaining a scalable and easy-to-understand stylesheet. This convention avoids conflicts and increases readability.
@Component({
/* ...
Other component metadata
... */
styles: [
`
:host {
display: block;
}
.internal-class {
color: blue;
}
`
]
})
export class InlineStyleComponent {
// Component logic for a component with inline styles
}
This code demonstrates how to use inline styles in an Angular component. The ':host' pseudo-class selector is used to style the component host element. This approach is useful for small and component-specific styles.