縮小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
我沒有深刻的形式知識。也許是別人。 –