Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add "Active" class when input field is not empty

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

like image 308
Jean-Francois Avatar asked Jun 28 '17 19:06

Jean-Francois


2 Answers

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

like image 126
JB Nizet Avatar answered Oct 30 '22 11:10

JB Nizet


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>
like image 39
taras-d Avatar answered Oct 30 '22 11:10

taras-d