ngClass and ngStyle
Sometimes you need to change the appearance of elements dynamically based on component data. Angular provides two powerful attribute directives for this: ngClass and ngStyle.
ngClass adds or removes CSS classes dynamically.
Ways to use ngClass:
<!-- String syntax -->
<div [ngClass]="'active highlighted'">String syntax</div>
<!-- Array syntax -->
<div [ngClass]="['active', 'highlighted']">Array syntax</div>
<!-- Object syntax (most common) -->
<div [ngClass]="{'active': isActive, 'highlighted': hasError}">Object syntax</div>
Complete example:
@Component({
selector: 'app-alert',
styles: [`
.success { background-color: green; color: white; }
.error { background-color: red; color: white; }
.warning { background-color: orange; color: black; }
.bold { font-weight: bold; }
`],
template: `
<div [ngClass]="getAlertClasses()">
{{ message }}
</div>
<button (click)="setSuccess()">Success</button>
<button (click)="setError()">Error</button>
<button (click)="setWarning()">Warning</button>
`
})
export class AlertComponent {
type = 'success';
message = 'Operation successful!';
isBold = true;
getAlertClasses() {
return {
'success': this.type === 'success',
'error': this.type === 'error',
'warning': this.type === 'warning',
'bold': this.isBold
};
}
setSuccess() { this.type = 'success'; this.message = 'Operation successful!'; }
setError() { this.type = 'error'; this.message = 'Something went wrong!'; }
setWarning() { this.type = 'warning'; this.message = 'Please check your input!'; }
}
ngStyle sets inline styles dynamically.
<div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px', 'background-color': bgColor}">
Styled text
</div>
textColor = 'blue';
fontSize = 16;
bgColor = 'yellow';
Two Minute Drill
- ngClass dynamically adds/removes CSS classes.
- Use object syntax: `{'class-name': condition}`.
- ngStyle dynamically sets inline styles.
- Use camelCase for style properties (fontSize not font-size).
- Both are attribute directives – no asterisk (*).
Need more clarification?
Drop us an email at career@quipoinfotech.com
