2016-07-29 62 views
3

我正在使用自定义指令,它应该为主机设置值属性。 问题是它不更新组件的模型,只更新元素值。Angular 2自定义指令不更新模型

这里是直播plnkr链接:https://plnkr.co/edit/lcT4q9EP3OEnuIDcGobC?p=preview

//our root app component 
import {Component} from 'angular2/core'; 
import { Directive, ElementRef, OnInit, HostListener } from 'angular2/core'; 

@Directive({selector: '[myData]'}) 

class MyDataDirective implements OnInit { 
    private el: any; 
    constructor(el: ElementRef) { 
    this.el = el.nativeElement 
    } 

    @HostListener('focus') onFocus() { 
    console.log("focus event triggered...") 
    this.el.setAttribute("value", "On Focus value") //Input value changes but model doesn't update 
    } 

    ngOnInit() { 
    console.log("oninit function called...") 
    this.el.setAttribute('value', 1234) 

    } 
} 


@Component({ 
    selector: 'my-app', 
    template: ` 
    <input type="text" placeholder="Enter text" [(value)]="inputValue" myData/> 
    `; 
    directives: [MyDataDirective] 
}) 

export class App { 
    constructor() { 
    this.inputValue = "Value from model" 
    } 
} 

回答

3

更新输入值属性不改变的值,我们可以看到

而且还从文档:

事实上,一旦我们开始数据绑定,我们就不再使用 HTML属性。我们不设置属性。我们正在设置DOM元素,组件和指令的 属性。

如果更改

this.el.setAttribute("value", "On Focus value") 

this.el.value = "On Focus value" 

应该更新您的输入,但不是模型。

如果您想更新模型,所以你应该知道在框中是香蕉结合[(value)]是一样的:

[value]="inputValue" (valueChange)="inputValue="$event" 

所以你的指令可能是这样的:

class MyDataDirective implements OnInit { 
    private el: any; 
    constructor(el: ElementRef) { 
    this.el = el.nativeElement 
    } 
    @Output() valueChange = new EventEmitter(); 

    @HostListener('focus') onFocus() { 
    console.log("focus event triggered...") 
    this.valueChange.emit("On Focus value"); 
    } 

    @HostListener('input') onInput() { 
    console.log("input event triggered...") 
    this.valueChange.emit(this.el.value); 
    } 

    ngOnInit() { 
    console.log("oninit function called...") 
    this.valueChange.emit("1234"); 

    } 
} 

Plunker Example

这篇文章可能b Ë兴趣为你