Skip to content Skip to sidebar Skip to footer

Register Model Changes To Mdl Input Elements

When integrating MDL with a framework, the framework will set the values for inputs directly, but the changes won't get noticed by the MDL libraries, as those are likely bound to c

Solution 1:

The best solution I have found for this is to use a directive. You can call checkDirty() on the element.

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

@Directive({
    selector: '[mdl]'
})
exportclassMDLimplementsAfterViewInit {
    constructor(private element: ElementRef) {
    }

    ngAfterViewInit() {
        componentHandler.upgradeAllRegistered();
    }

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

Then, in your template simply include this directive in the parent div of the mdl input

<div mdl class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label mdl-cell mdl-cell--5-col mdl-cell--8-col-tablet mdl-cell--4-col-phone">
    <labelclass="mdl-textfield__label"for="promoCode_{{inRibbon}}">Promo code</label><inputclass="mdl-textfield__input"type="text"id="promoCode"name="promoCode_{{inRibbon}}" [ngModelOptions]="{standalone: true}" [(ngModel)]="itemAvailabilityRequest.promoCode"></div>

Solution 2:

Updated answer:

binding to the class list, https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngClass, might be a better way:

example:

<div class="mdl-textfield mdl-js-textfield mdl-text-field--floating-label"
    [class.is-dirty]=" val != null && val != '' ">

or for mdl-tabs:

<div class="mdl-tabs__panel"
    [class.is-active]="val_is_active_tab">

or for mdl-checkboxes:

<label class="mdl-radio mdl-js-radio mdl-js-ripple-effect"
      [class.is-checked]="val == 1">

Original answer:

For my project my temp solution was to put in some very un-angular2 code:

private thingsToDirty = [];
ngAfterViewChecked() {
    for (let id ofthis.thingsToDirty) {
        letel: any = document.getElementById(id);
        if (el != undefined && 
        el.parentNode.className.indexOf("is-dirty") == -1) {
            el.parentNode.className += " is-dirty";
        }
    }
    this.thingsToDirty.length = 0;
}

ngOnInit() {
    this.something.getJSONfromServer().subscribe( data => {
        this.thing = data;
        this.thingsToDirty.push('thing_id');
    });
}

Post a Comment for "Register Model Changes To Mdl Input Elements"