0
0
Angularframework~30 mins

ngStyle for dynamic styles in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Dynamic Styling with ngStyle in Angular
📖 Scenario: You are building a simple Angular component that changes the style of a message dynamically based on user interaction. This is common in real-world apps where styles need to update without reloading the page.
🎯 Goal: Create an Angular standalone component that uses ngStyle to apply dynamic styles to a message. The styles will change based on a configuration variable.
📋 What You'll Learn
Create a standalone Angular component named DynamicStyleComponent.
Define a message string property with the text 'Welcome to dynamic styling!'.
Create a configuration object called styleConfig with CSS properties for color and font size.
Use ngStyle in the template to apply styleConfig to the message paragraph.
Add a button that toggles the color between 'blue' and 'green' dynamically.
💡 Why This Matters
🌍 Real World
Dynamic styling is common in web apps to provide visual feedback, highlight important information, or adapt UI based on user actions without reloading the page.
💼 Career
Understanding ngStyle and dynamic styling is essential for Angular developers to build interactive and user-friendly interfaces.
Progress0 / 4 steps
1
Create the Angular component and message
Create a standalone Angular component named DynamicStyleComponent. Inside the component class, create a public string property called message and set it to 'Welcome to dynamic styling!'.
Angular
Need a hint?

Use message = 'Welcome to dynamic styling!' inside the component class.

2
Add a style configuration object
Inside the DynamicStyleComponent class, create a public object called styleConfig with two properties: color set to 'blue' and fontSize set to '1.5rem'.
Angular
Need a hint?

Define styleConfig as an object with color and fontSize properties.

3
Use ngStyle to apply styles in the template
In the component's template, add a paragraph element that displays the message. Use the Angular directive [ngStyle] to bind the styleConfig object to the paragraph's styles.
Angular
Need a hint?

Use [ngStyle]="styleConfig" on the paragraph to apply styles dynamically.

4
Add a button to toggle the text color dynamically
Add a button below the paragraph in the template with the text Toggle Color. In the component class, create a method called toggleColor() that switches styleConfig.color between 'blue' and 'green'. Bind the button's (click) event to this method.
Angular
Need a hint?

Create a toggleColor() method that changes styleConfig.color between 'blue' and 'green'. Bind it to the button's click event.