我有一个指令应该根据输入的 ngModel 更新一些内部值。当用户手动输入值时,这可以正常工作,但当 ngModel 从组件更改时,这将停止工作。
组件模板:
<input [(ngModel)]="myValue" myExample>
Run Code Online (Sandbox Code Playgroud)
更改组件中的 ngModel:
ngOnInit() {
this.getDataFromApi()
.then((result) => {
this.myValue = result;
})
}
Run Code Online (Sandbox Code Playgroud)
指示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果在 API 调用后从控制器更新 ngModel,则指令中的 ngModelChange 不会触发,并且 _valueInDirective 也不会更新。如何确保每次更新 ngModel 时,指令中的值也会更改?
我尝试过DoCheckhook,但结果效率极低。这是我最终得到的解决方案,我对此感到满意:
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
});
}
}
Run Code Online (Sandbox Code Playgroud)