Pre-populated MDL text field causes a problem with Angular2

I am working on a project with pure MDL and Angular2, but I have a problem with text fields and ngModel.

When the angular component sets any value to the object used in the model, the MDL component does not start checking for dirtiness and validity, I think this is because the event that 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 immediately after creating the component:

enter image description here

Note that the input matters (provided by the angular component), but the placeholder is still above the input, and the input is red, indicating that this is incorrect.

After some research, I developed a solution for directives:

 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 have another or better solution for this?

+5
source share

Source: https://habr.com/ru/post/1263705/


All Articles