输入元素上的Angular 2双数据绑定不起作用

时间:2016-11-06 09:22:37

标签: javascript angular data-binding onchange

参考下面的代码,只要输入值改变,就会调用textchange函数。但是,InputMaskComponent的text属性永远不会更改。不确定我的代码有什么问题。

InputMaskComponent.ts

import { Component, ViewChild, AfterViewInit, ElementRef, Attribute } from '@angular/core';

@Component({
    selector:'inputs:mask',
    templateUrl:'InputMaskComponent.html'
})
export class InputMaskComponent{
    pattern: string;
    text: string;
    dom: Element;
    constructor(el:ElementRef, @Attribute('pattern') pattern:string){
        this.dom = el.nativeElement;
        this.pattern = pattern;
    }
    textchange(event:any){
        console.log(this.text, event);
    }

}

InputMaskComponent.html

<div>
    <input  type="text" 
            [placeholder]="pattern" 
            (input)="textchange($event)" 
            [(value)]="text" />
    <span #child class="hidden"><ng-content></ng-content></span>
</div>

RootComponent.html

<input:mask pattern="(###) ### - ###">(012) 345 - 678</input:mask>

1 个答案:

答案 0 :(得分:1)

[(value)]="text"

表示你绑定

    组件类的
  • text属性为value元素的<input>属性
  • valueChange事件到事件处理程序text = $event

<input>元素不会发出valueChange事件。

另见https://angular.io/docs/ts/latest/guide/template-syntax.html#!#two-way