我有一个指令应该根据输入的ngModel更新一些内部值。当用户手动键入值时,这可以正常工作,但当从组件更改ngModel时停止工作。
组件模板:
<input [(ngModel)]="myValue" myExample>
更改组件中的ngModel:
ngOnInit() {
this.getDataFromApi()
.then((result) => {
this.myValue = result;
})
}
指令:
import { Directive, OnInit } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[myExample][ngModel]',
providers: [NgModel],
host: {
'(ngModelChange)' : 'onModelChange($event)',
}
})
export class myExampleDirective implements OnInit {
private _valueInDirective;
constructor(private _element: ElementRef, private _model: NgModel) { }
onModelChange(event) {
this._valueInDirective = event;
}
}
如果在API调用后从控制器更新了ngModel,则指令中的ngModelChange不会触发,并且不会更新_valueInDirective。如何确保每次更新ngModel时,指令中的值也会改变?
答案 0 :(得分:1)
我尝试使用DoCheck
钩子,但结果非常低效。这是我最终得到的解决方案,我很满意:
import { Directive, OnInit } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[myExample][ngModel]',
providers: [NgModel]
})
export class myExampleDirective implements OnInit {
private _valueInDirective;
constructor(private _model: NgModel) { }
ngOnInit() {
this._model.valueChanges.subscribe((event) => {
this._valueInDirective = event;
// do other stuff
});
}
}