As others mentioned here you don't really need separate directive for such small thing, but if you want it that way... ok, here it is.
UPDATE
Actually, it can be done even simpler. I've updated the code.
app.module.ts
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';
import {AppMdbInputInitDirective} from './app-mdb-input-init.directive';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
AppMdbInputInitDirective
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
app.component.ts
import {Component} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
formGroup: FormGroup;
activeFlag$: Observable<boolean>;
constructor(fb: FormBuilder) {
this.formGroup = fb.group({
firstName: fb.control('')
});
this.activeFlag$ = this.formGroup.get('firstName').valueChanges.map(v => !!v);
}
}
app.component.css
.active {
color: red;
}
app.component.html
<div class="md-form" [formGroup]="formGroup">
<input type="text" name="" id="FirstName" class="form-control" formControlName="firstName">
<label for="FirstName" [appMdbInputInit]="activeFlag$ | async" labelClassName="active">First Name</label>
</div>
And, finally, most interesting part - app-mdb-input-init.directive.ts
import {Directive, ElementRef, Input, Renderer2} from '@angular/core';
@Directive({
selector: '[appMdbInputInit]'
})
export class AppMdbInputInitDirective {
@Input()
labelClassName: string;
@Input()
set appMdbInputInit(val: boolean) {
if (val) {
this.renderer.addClass(this.elementRef.nativeElement, this.labelClassName);
} else {
this.renderer.removeClass(this.elementRef.nativeElement, this.labelClassName);
}
}
constructor(private elementRef: ElementRef, private renderer: Renderer2) {
}
}