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

时间:2016-07-29 15:22:12

标签: angular

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

这是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"
  }
}

1 个答案:

答案 0 :(得分:3)

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

还有文档:

  

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

如果你改变了

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

this.el.value = "On Focus value"

它应该更新你的输入而不是模型。

如果您想要更新模型,那么您应该知道 banana in box 绑定[(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

本文可能对您感兴趣

相关问题