[英]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");
}
}
本文可能对您有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.