6

I am working in a project with pure MDL and Angular2, but I am having an issue with the textfields and ngModel.

When the angular component set some value to the object used in the model the MDL component doesn't run the dirty and validity check correctly, I think it happens because the event it needs is not triggered.

This is the input code:

<div class="mdl-textfield mdl-js-textfield">
    <input type="text" required class="mdl-textfield__input" id="field-sample" name="field-sample" [(ngModel)]="obj.name"></input>
    <label class="mdl-textfield__label" for="field-sample">Placeholder label</label>
</div>

This is the result just after the component is created:

enter image description here

Notice that the input has a value (provided by the angular component), but the placeholder label still over the input and the input is red indicating this is invalid.

After some research I have developed a Directive solution:

import {AfterViewChecked, AfterViewInit, Directive, ElementRef} from '@angular/core';
declare var componentHandler: any;

/**
 * Created to make MDL field validation and dirt check compatible with angular
 * Used in <input> and <textarea> tags
 */
@Directive({
    selector: '[mdl-textfield]'
})
export class MDLTextFieldDirective implements AfterViewChecked, AfterViewInit {

    constructor(private element: ElementRef) {
    }

    ngAfterViewInit() {
        componentHandler.upgradeAllRegistered();
    }

    ngAfterViewChecked() {
        let mdlField = this.element.nativeElement.MaterialTextfield;
        if(mdlField) {
            mdlField.checkDirty();
            mdlField.checkValidity();
        }
    }
}

Does anyone has another or better solution for that?

Henrique Rotava
  • 481
  • 5
  • 11

0 Answers0