2016-07-29 64 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 Ë興趣爲你