缩小plunkr:https://plnkr.co/edit/gGCiYjcq70xaewn3n22F?p=preview角2不能设置默认值
@Input() model: any;
propagateChange = (_: any) => {};
registerOnChange(fn) {
this.propagateChange = fn;
}
registerOnTouched() {}
writeValue(value: any) {
if (value !== undefined) {
this.model = value;
}
}
ngOnInit() {
// Sets the model properly, but it doesn't show up in the view or outside of the component
if (!this.model && this.isRequired) {
this.model = options[0];
}
this.propagateChange(this.model);
}
用法:
<form #myForm="ngForm">
<custom-select #fuel="ngModel" [(ngModel)]="model.fuel" [options]="fuels" [isRequired]="true" name="fuel"></custom-select>
</form>
我自定义选择实现ControlValueAccessor
,但我不能当组件首先在ngOnInit
方法中初始化时,让它设置一个默认值。 model
已正确设置在组件内部,但未反映在组件的视图中或外部。但是,如果我然后通过选择其他选项来改变它的价值。有没有人知道这是为什么?
我想这是一个变化检测问题,因为'ngOnInit()'从变化检测调用。但我不知道如何解决它。 –
@GünterZöchbauer这是一个无赖。真正重要的是让这个工作嗯..如果你碰巧找到一个解决方案,我会奖励你一个坚实的赏金。直到那时我想我将不得不尝试一切尝试.. – Chrillewoodz
我没有深刻的形式知识。也许是别人。 –