Angular Inline Styles with Style Bindings and the NgStyle Directive Examples
Example of how to dynamically set the font size of an element using style binding in Angular:
@Component({
selector: 'app-root',
standalone: true,
template: `
<div [style.font-size.px]="fontSize">
This text's font size is dynamically set to {{ fontSize }} pixels.
</div>
<button (click)="increaseFontSize()">Increase Font Size</button>
`,
})
export class App {
fontSize: number = 16;
increaseFontSize() {
this.fontSize += 2;
}
}
Example of how to use the ngStyle directive in Angular to dynamically apply multiple styles to an element based on component logic and user interaction:
@Component({
selector: 'app-root',
standalone: true,
template: `
<div [ngStyle]="divStyles">
This div's styles are dynamically set.
</div>
<button (click)="toggleStyles()">Toggle Styles</button>
`,
imports: [CommonModule],
})
export class App {
divStyles: { [key: string]: any } = {
'background-color': 'lightblue',
color: 'black',
'font-size': '16px',
'padding.px': 20,
};
applyAlternateStyles: boolean = true;
toggleStyles() {
if (this.applyAlternateStyles) {
this.divStyles = {
'background-color': 'lightgreen',
color: 'white',
'font-size': '20px',
'padding.px': 30,
};
} else {
this.divStyles = {
'background-color': 'lightblue',
color: 'black',
'font-size': '16px',
'padding.px': 20,
};
}
this.applyAlternateStyles = !this.applyAlternateStyles;
}
}