将模型更改注册到MDL输入元素 [英] Register model changes to MDL input elements

查看:107
本文介绍了将模型更改注册到MDL输入元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将MDL与框架集成时,框架将直接设置输入值,但是MDL库不会注意到更改,因为这些更改很可能会绑定到click和change事件.例如,如果我有:

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 click and change events. For example, if I have:

<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
    <input class="mdl-textfield__input" type="text" id="joke" pattern="-?[0-9]*(\.[0-9]+)?">
    <label class="mdl-textfield__label" for="joke">Joke...</label>
    <span class="mdl-textfield__error">Input is not a number!</span>
</div>

,然后使用一些javascript更改值:

but then change the value with some javascript:

document.getElementById('joke').value=text;

元素标签不会移动,并被文本覆盖.简而言之,未设置 is-dirty 类.

the element label does not move, and is covered by the text. In short, the is-dirty class is not set.

这是一个更详细地显示问题的示例. https://plnkr.co/6pAh7ApQT8TUUS9G9QBg

Here is an example that shows the issue in more detail. https://plnkr.co/6pAh7ApQT8TUUS9G9QBg

我目前正在Angular2中从事一个项目,但我认为总体问题与框架无关.我希望有比答案"更好的解决方案.

I am currently working on a project in Angular2, but I think the overall issue is framework agnostic. I'm hoping some better solutions than my 'answer'.

推荐答案

为此找到的最佳解决方案是使用指令.您可以在元素上调用checkDirty().

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';
declare var componentHandler: any;

@Directive({
    selector: '[mdl]'
})
export class MDL implements AfterViewInit {
    constructor(private element: ElementRef) {
    }

    ngAfterViewInit() {
        componentHandler.upgradeAllRegistered();
    }

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

然后,在您的模板中,只需将此指令包含在mdl输入的父div中即可

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">
    <label class="mdl-textfield__label" for="promoCode_{{inRibbon}}">Promo code</label>
    <input class="mdl-textfield__input" type="text" id="promoCode" name="promoCode_{{inRibbon}}" [ngModelOptions]="{standalone: true}" [(ngModel)]="itemAvailabilityRequest.promoCode">
</div>

这篇关于将模型更改注册到MDL输入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆