Angular Component Styles
Component styles define the visual appearance of an Angular component. Angular allows styles to be associated with an individual component so that its user interface can be organized and maintained easily.
What are Component Styles?
Component styles are CSS rules associated with a specific Angular component. They control properties such as colors, fonts, spacing, borders and layout.
Component Styling Flow
Component
Defines the Angular component.
CSS
Defines visual styles.
Angular
Associates styles with the component.
Browser
Displays the styled UI.
Basic Component with Styles
import { Component } from '@angular/core';
@Component({
selector: 'app-student',
templateUrl: './student.component.html',
styleUrl: './student.component.css'
})
export class StudentComponent {
studentName = 'Sam';
}
The component is connected to its stylesheet using styleUrl.
Component CSS File
CSS rules can be written in the component stylesheet.
h2 {
color: #4c1d95;
font-size: 28px;
}
p {
color: #475569;
font-size: 18px;
}
HTML Template
<h2>
Student Details
</h2>
<p>
Student Name: {{ studentName }}
</p>
Expected Output
Student Details
Student Name: Sam
Inline Component Styles
For small components, styles can also be written directly inside the component metadata using the styles property.
import { Component } from '@angular/core';
@Component({
selector: 'app-student',
template: `
<h2>Student Details</h2>
<p>Student Name: Sam</p>
`,
styles: [`
h2 {
color: #4c1d95;
}
p {
font-size: 18px;
}
`]
})
export class StudentComponent {
}
External Styles vs Inline Styles
Common CSS Properties
Color
color
Changes text color.
Background
background
Changes background appearance.
Typography
font-size
Controls text size.
Spacing
margin / padding
Controls element spacing.
Styling HTML Classes
CSS classes can be created in the component stylesheet and applied to HTML elements.
.student-card {
border: 1px solid #ddd6fe;
padding: 20px;
border-radius: 8px;
}
.student-name {
color: #4c1d95;
font-weight: 700;
}
<div class="student-card">
<h2 class="student-name">
Sam
</h2>
</div>
Using styleUrl
The styleUrl property connects the component with its external stylesheet.
@Component({
selector: 'app-student',
templateUrl: './student.component.html',
styleUrl: './student.component.css'
})
Component Style Scope
Angular component styles are associated with the component rather than simply being treated as one large application stylesheet.
Component Styling Best Practices
Keep component-specific styles close to the component.
Use meaningful CSS class names.
Avoid unnecessary duplication of styles.
Keep styles organized and easy to maintain.
Summary
Angular component styles control the visual appearance of a component.
Styles can be stored in an external CSS file using styleUrl or written directly using the styles property.
Keeping component styles organized makes Angular applications easier to maintain and understand.