簡體   English   中英

Angular 2自定義指令不更新模型

[英]Angular 2 custom directive doesn't update the model

我正在使用自定義指令,它應該將值屬性設置為主機。 問題是它不更新組件的模型,只更新元素值。

這是live 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"
  }
}

更新輸入值屬性不會更改我們可以看到的值

還有文檔:

實際上,一旦我們開始數據綁定,我們就不再使用HTML屬性了。 我們沒有設置屬性。 我們正在設置DOM元素,組件和指令的屬性。

如果你改變了

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

this.el.value = "On Focus value"

它應該更新你的輸入而不是模型。

如果要更新模型,那么您應該知道綁定[(value)]中的banana與以下內容相同:

[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示例

本文可能對您有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM