我有一个指令应该根据输入的 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;
}
}
如果 ngModel 在 API 调用后从 Controller 更新,指令中的 ngModelChange 不会触发并且 _valueInDirective 不会更新。如何确保每次更新 ngModel 时,指令中的值也会更改?
最佳答案
我尝试了 DoCheck
钩子(Hook),但结果证明它非常低效。这是我最终得到的解决方案,我很满意:
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
});
}
}
关于angular - 当 ngModel 在没有用户输入的情况下从组件更改时,ngModelChange 不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45862382/