Angular - Style Binding
Style Binding is used to set a styles dynamically for HTML elements. We can set the inline styles of an HTML element using the style binding in angular. You can also add styles conditionally to an element, hence creating a dynamically styled element.
app/src/app.component.ts
import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { name:string='Ram'; age:number=20; isError:boolean=false; msg:any='purple'; }
- name:string='Ram'; Declares a public property name of type string and initializes it with the value 'Ram'
- age: number = 20; Declares a public property age of type number and initializes it with the value 20
- isError:boolean=false; Declares a public property isError of type boolean and initializes it with the value false
- msg:any='purple'; Declares a public property msg of type any and initializes it with the value 'purple'
app/src/app.component.html
<html> <head> <title>Style Binding</title> </head> <body> <div> <!--Single Style Binding--> <h1 [style.color]="'blue'">Sample Website</h1> <!--Using Conditional Operator Style Binding--> <h1 [style.color]="isError?'red':'green'">Welcome {{name}} age is {{age}}</h1> <!--Component Property Style Binding--> <h1 [style.color]="msg">Hello World</h1> </div> </body> </html>
Run the Angular Application use the command is given below
ng serve
Copy the URL: http://localhost:4200/ and run in your browser
Output
