简体   繁体   English

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

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

I'm using custom directive and it should set value attribute to the host. 我正在使用自定义指令,它应该将值属性设置为主机。 Issue is it doesn't update the model of the component and only updates the element value. 问题是它不更新组件的模型,只更新元素值。

Here is the live plnkr link: https://plnkr.co/edit/lcT4q9EP3OEnuIDcGobC?p=preview 这是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"
  }
}

Updating input value attribute doesn't change value which we can see 更新输入值属性不会更改我们可以看到的值

And also from documentation: 还有文档:

In fact, once we start data binding, we are no longer working with HTML attributes. 实际上,一旦我们开始数据绑定,我们就不再使用HTML属性了。 We aren't setting attributes. 我们没有设置属性。 We are setting the properties of DOM elements, components, and directives. 我们正在设置DOM元素,组件和指令的属性。

If you change 如果你改变了

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

with

this.el.value = "On Focus value"

it should update your input but not model. 它应该更新你的输入而不是模型。

If you want to update model so you should know that banana in box binding [(value)] is the same as: 如果要更新模型,那么您应该知道绑定[(value)]中的banana与以下内容相同:

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

So your directive might look like: 所以您的指令可能如下所示:

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

This article might be interested for you 本文可能对您有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM