【问题标题】:Angular 2 custom directive doesn't update the modelAngular 2 自定义指令不会更新模型
【发布时间】:2016-12-04 09:04:41
【问题描述】:

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

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

【问题讨论】:

    标签: angular


    【解决方案1】:

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

    还有来自文档:

    事实上,一旦我们开始数据绑定,我们就不再使用 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

    你可能会对这篇文章感兴趣

    【讨论】:

      猜你喜欢
      • 2020-03-03
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 2018-11-15
      相关资源
      最近更新 更多