2016-07-29 6 views
3

私はカスタムディレクティブを使用しています。これはホストにvalue属性を設定する必要があります。 問題はコンポーネントのモデルを更新せず、要素値のみを更新します。ここで角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.value = "On Focus value" 

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

を変更する場合、それはあなたの入力ではなく、モデルを更新する必要があります。

あなたが[(value)]を結合ボックスでバナナが同じであることを知っている必要がありますので、モデルを更新する場合:

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:だからあなたのディレクティブは次のようになります

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

この記事はb電子興味を持ってあなたのための

関連する問題