Reputation: 31
Do we have any option to add/append CSS class to a reactive form control from the component in angular?
Upvotes: 3
Views: 5171
Reputation: 399
The most dynamic way of adding a class to an element from *.ts is to query the element via @ViewChild and then use Renderer2 API to add a CSS class you need:
@ViewChild('input') input: ElementRef;
constructor(private renderer: Renderer2) {}
ngAfterViewInit() {
this.addClass();
}
addClass() {
this.renderer.addClass(this.input.nativeElement, 'my-class');
}
See my stackblitz for a full example.
A more simple alternative is binding to [ngClass]:
<input [ngClass]="{ 'my-class-1': condition1, 'my-class-2': condition2 }">
(condition1
and condition2
are to be defined in your *.ts and return boolean value)
or
<input [ngClass]="classProvider">
where classProvider is a function, getter or just a property:
classProvider() {
return 'my-class';
}
get classProvider() {
return 'my-class'
}
classProvider = 'my-class';
or just use [class] binding:
<input [class.my-class]="condition">
where condition
returns true
if my-class
should be applied and false
if it should not.
Upvotes: 1
Reputation: 81
Yes, you can make custom css objects in ts, and you can use [ngStyle];
For example
//you can do it by statements, or by function, whatever you want
<input [formControlName]="..." [ngStyle]="border()" />
in ts:
border() {
//you can do whatever you want, pass in value, or variables
return {
border: '1px solid blue'
}
}
Upvotes: 0