我不知道为什么,但是在我点击页面上的某个地方之前,我的组件有时不会将模型发布到组件的视图中。该组件正在使用OnPush
作为其ChangeDetectionStrategy
,我正在尝试发送,传播更改并标记路径以进行更改检测,但似乎没有任何效果。
编辑:我也在使用ControlValueAccessor
使其与表单一起使用,我不确定它是否已在此处正确完成。
我猜@Output()
的{{1}}有问题,但我尝试了不同的解决方案,但我无法解决它:
ngModel/model
我觉得奇怪的是,所有观点都没有发生这种情况。但我没有发现任何有关视图的内容,并且模型在@Output('ngModelChange') modelChange: EventEmitter<any> = new EventEmitter(true);
@Output('ngModelChange') modelChange: EventEmitter<any> = new EventEmitter();
@Output() ngModelChange: EventEmitter<any> = new EventEmitter();
中正确设置,但视图是没有更新所有的时间。
组件:
ngOnInit
查看:
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SelectComponent),
multi: true
}
]
})
export class SelectComponent implements ControlValueAccessor, OnDestroy, OnInit {
@Input('ngModel') model: any;
@Output() ngModelChange: EventEmitter<any> = new EventEmitter(true);
constructor(private changeDetector: ChangeDetectorRef) {}
propagateChange = (_: any) => {};
registerOnChange(fn) {
this.propagateChange = fn;
}
registerOnTouched() {}
writeValue(value: any) {
if (value !== undefined) {
this.model = value;
}
}
...
ngOnInit() {
// Set some default values
this.isRequired = this.isRequired || false;
this.isDisabled = this.isDisabled || false;
this.placeholder = this.placeholder || '';
this.options = this.options || [];
this.optionsLabel = this.optionsLabel || 'name';
this.uniqueKey = this.uniqueKey || 'id';
if (!this.model && this.isRequired) {
this.model = this.options[0];
}
else if (!this.isRequired) {
this.model = null;
}
console.log(this.model);
this.propagateChange(this.model);
this.changeDetector.markForCheck();
this.ngModelChange.emit(this.model);
}
...
}
像这样使用它:
...
<div>{{model ? model[optionsLabel] : placeholder}}</div>
...