我在启用Ivy编译的情况下将大型应用程序升级到Angular 9,并且遇到了将NgModel注入自定义指令的行为似乎发生了变化的情况
使用此指令时,使用IVY编译时,注入的NgModel在版本7和版本8/9之间是不同的。
禁用常春藤编译时不会发生。
指令(tabSelect)
import { Directive, AfterViewInit, OnDestroy, Optional } from '@angular/core';
import { NgModel } from "@angular/forms";
import { MatAutocompleteTrigger } from '@angular/material/autocomplete';
@Directive({
selector: '[tabSelect]',
providers: [NgModel]
})
export class TabSelectDirective implements AfterViewInit, OnDestroy {
observable: any;
onChange: any;
constructor(@Optional()
private autoTrigger: MatAutocompleteTrigger,
private ngModel: NgModel) { }
ngAfterViewInit() {
this.observable = this.autoTrigger.panelClosingActions.subscribe(x => {
if (this.autoTrigger.activeOption && this.autoTrigger.activeOption.value) {
if (this.ngModel.model !== this.autoTrigger.activeOption.value) {
this.ngModel.update.emit(this.autoTrigger.activeOption.value);
this.autoTrigger.autocomplete.optionSelected.emit();
}
} else {
console.log(this.ngModel);
console.log(this.autoTrigger);
if (!this.ngModel.viewModel || this.ngModel.viewModel === "")
this.ngModel.update.emit(null);
};
});
}
ngOnDestroy() {
this.observable.unsubscribe();
}
};
在HTML中使用指令
<mat-form-field appearance="outline" color="primary" class="mat-input-no-validation pull-right"
style="width: 130px; margin-left: 10px">
<mat-label>Document Group</mat-label>
<input matInput
placeholder="Search.."
name="documentGroupInput"
spellcheck="false"
[(ngModel)]="documentNode.documentGroup"
[matAutocomplete]="documentGroupAuto"
#documentGroupCtrl="ngModel"
tabSelect />
<div class="small-progress-spinner-container" [hidden]="!documentGroupSearching">
<mat-progress-spinner [diameter]="15" [mode]="'indeterminate'"></mat-progress-spinner>
</div>
<mat-autocomplete #documentGroupAuto="matAutocomplete">
<mat-option *ngFor="let documentGroup of documentGroupResults; trackBy:formatters.trackIndex" [value]="documentGroup">
<div class="autocomplete-option">
{{ documentGroup }}
</div>
</mat-option>
</mat-autocomplete>
</mat-form-field>
[检查注入到指令中的NgModel时,在Angular 7中,我们看到了控件名称
NgModel {_parent: NgForm, name: "documentGroupInput", valueAccessor: MatAutocompleteTrigger, _rawValidators: Array(0), _rawAsyncValidators: Array(0), …}
Angular 9中的英雄,我们没有
NgModel {_parent: NgForm, name: null, valueAccessor: MatAutocompleteTrigger, _rawValidators: Array(0), _rawAsyncValidators: Array(0), …}
[这使我相信,注入的NgModel实际上不是Ivy中控件本身的模型,这由赋值和发出更改后的事件的方法不再起作用
任何想法都有什么变化,我该如何解决?
谢谢
从providers: [NgModel]
属性中删除@Directive
应该可以解决此问题。一旦找出原因,我将更新此答案。