I'm trying to create an Angular 4 Directive that will add class="active"
on the label when the textfield is not empty
<div class="md-form">
<input appMdbInputInit type="text" name="" id="FirstName"
class="form-control" formControlName="firstName">
<label for="FirstName" >First Name</label>
</div>
Result that I expect when textfield is not empty
<div class="md-form">
<input appMdbInputInit type="text" name="" id="FirstName"
class="form-control" formControlName="firstName">
<label class="Active" for="FirstName" >First Name</label>
</div>
How can I do that ?
Thanks a lot
You don't need any custom directive to do that. Example:
<form [formGroup]="group">
<input appMdbInputInit type="text" name="" id="FirstName"
class="form-control" formControlName="firstName">
<label [class.Active]="group.get('firstName').value.length" for="FirstName">First Name</label>
</form>
Demo: http://plnkr.co/edit/SUmIVCaWnJzjU7j0XHwj?p=preview
You can create directive and inject FormControlName
instance to listen to value changes. And add or remove label active class when value changes.
Directive
import { Directive, OnInit, OnDestroy, ElementRef } from '@angular/core';
import { FormControlName } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';
@Directive({
selector: '[setLabelActive]'
})
export class SetLabelActiveDirective implements OnDestroy {
valueSub: Subscription;
constructor(
private el: ElementRef,
private formControlName: FormControlName // Inject FormControlName
) {
}
ngOnInit() {
// Listen value changes
this.valueSub = this.formControlName.valueChanges.subscribe(value => {
// Get label
const inputId = this.el.nativeElement.getAttribute('id'),
label = document.querySelector(`label[for="${inputId}"]`);
// Toggle `active` class
if (label) {
label.classList.toggle('active', value);
}
});
}
ngOnDestroy() {
// Unlisten value changes
this.valueSub.unsubscribe();
}
}
Usage
<form [formGroup]="myForm">
<div>
<input setLabelActive type="text" id="FirstName" formControlName="firstName">
<label for="FirstName">First Name</label>
</div>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With