缩小后的plunkr:https://plnkr.co/edit/gGCiYjcq70xaewn3n22F?p=preview
@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ünter ZöchbauerwriteValue
方法内设置默认值。https://plnkr.co/edit/k6WpY4ERzH3fZ2QgZIz2?p=preview 因为writeValue
总是从NgModel组件触发,并且它会在你的组件中的ngOnInit之后发生。你还可以看到我如何通过setter属性(@Input() set model(val)
)检查模型。 - yurzui(_: any) => {}
,没有任何影响。 - yurzui