gpt4 book ai didi

Angular 2 无法为 ControlValueAccessor 组件设置默认值

转载 作者:搜寻专家 更新时间:2023-10-30 21:40:54 27 4
gpt4 key购买 nike

按比例缩小 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 已在组件内部正确设置,但未反射(reflect)在 View 中或组件外部。但是,如果我随后通过选择其他一些选项来更改该值,它会起作用。有人知道这是为什么吗?

最佳答案

你可以使用下面的方法让它工作

@Output() ngModelChange = new EventEmitter();

ngOnInit() {
...
this.ngModelChange.emit(this.model);
}

https://plnkr.co/edit/VQJSDLU9TP2rVBmNeTNr?p=preview

关于Angular 2 无法为 ControlValueAccessor 组件设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40585566/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com