0
0
Angularframework~30 mins

Component styles and encapsulation in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Component styles and encapsulation
📖 Scenario: You are building a simple Angular component that displays a user profile card. You want to style this card with a background color and padding. To keep styles organized and avoid affecting other parts of the app, you will use Angular's component style encapsulation.
🎯 Goal: Create an Angular standalone component called UserProfileComponent with a template showing a user name inside a <div>. Add styles to give the <div> a light blue background and some padding. Use Angular's default style encapsulation to keep these styles local to the component.
📋 What You'll Learn
Create a standalone Angular component named UserProfileComponent
Add a template with a <div> containing the text User: Alice
Add component styles to set the div background color to light blue and padding to 1rem
Use Angular's default style encapsulation (Emulated) to keep styles local
💡 Why This Matters
🌍 Real World
Component style encapsulation is essential in Angular apps to keep styles modular and prevent unwanted side effects across the app.
💼 Career
Understanding Angular component styles and encapsulation is a key skill for frontend developers working with Angular to build maintainable and accessible UI components.
Progress0 / 4 steps
1
Create the UserProfileComponent with template
Create a standalone Angular component named UserProfileComponent with a template that contains a <div> showing the text User: Alice. Use the @Component decorator with standalone: true and include the selector as app-user-profile.
Angular
Need a hint?

Use the @Component decorator with standalone: true and define the template inline.

2
Add component styles for background and padding
Add a styles array to the @Component decorator with CSS that sets the div background color to lightblue and padding to 1rem.
Angular
Need a hint?

Use the styles property with an array containing a CSS string targeting the div.

3
Set style encapsulation to Emulated explicitly
Add the encapsulation property to the @Component decorator and set it to ViewEncapsulation.Emulated to explicitly use Angular's default style encapsulation.
Angular
Need a hint?

Import ViewEncapsulation from @angular/core and set encapsulation to ViewEncapsulation.Emulated.

4
Add accessibility role and aria-label to the div
Add role="region" and aria-label="User Profile Card" attributes to the <div> in the component template to improve accessibility.
Angular
Need a hint?

Add role="region" and aria-label="User Profile Card" inside the div tag in the template string.