gpt4 book ai didi

angular - 自定义组件值未使用 Angular Reactive Form 进行更新

转载 作者:行者123 更新时间:2023-12-02 18:53:04 25 4
gpt4 key购买 nike

我创建了一个扩展 primeng spinner 的自定义输入组件组件,但是当我将它与 Angular Reactive Form 一起使用时,组件的模型值不会更新。我有stackblitzed我的问题,以便于调试。这是我的组件的代码:

import {Component, EventEmitter, forwardRef, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';
import {Spinner} from 'primeng/primeng';

@Component({
selector: 'rd-spinner',
template: `
<p-spinner [formControl]="rdSpinner"
[step]="step"
[min]="min"
[max]="max"
[placeholder]="placeholder"
[disabled]="disabled"
[readonly]="readonly"
[maxlength]="maxlength"
[size]="size"
[tabindex]="tabindex"
[inputId]="tabindex"
[type]="type"
[required]="required"
[name]="name"
[inputStyle]="inputStyle"
[inputStyleClass]="inputStyleClass"></p-spinner>
`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => RdSpinnerComponent),
multi: true
}]
})
export class RdSpinnerComponent implements ControlValueAccessor, OnInit {

@ViewChild(Spinner) private _spinner: Spinner;
rdSpinner: FormControl;

// Required to implement interface ControlValueAccessor
private _onChange : Function = () => {};
private _onTouched : Function = () => {};

// Those inputs at given directly to primeng spinner
@Input() step: number = 1;
@Input() min: number;
@Input() max: number;
@Input() placeholder: string;
@Input() disabled: boolean;
@Input() readonly: boolean;
@Input() maxlength: number;
@Input() size: number;
@Input() tabindex: number;
@Input() inputId: string;
@Input() type: string = 'text';
@Input() required: boolean;
@Input() name: string;
@Input() inputStyle: any;
@Input() inputStyleClass: string;
@Output() onChange: EventEmitter<any> = new EventEmitter();
@Output() onFocus: EventEmitter<any> = new EventEmitter();
@Output() onBlur: EventEmitter<any> = new EventEmitter();

constructor() {
}

ngOnInit() {
this.rdSpinner = new FormControl();

if (this._spinner) {
const origParseValue = this._spinner.parseValue;
this._spinner.parseValue = (val: string): number => {
let value: number;

if (val.trim() === '') {
value = null;
}
else {
value = origParseValue.call(this._spinner, val);
}

return value;
}
}
}

registerOnChange(fn: any): void {
this._onChange = fn;
}

registerOnTouched(fn: any): void {
this._onTouched = fn;
}

writeValue(value: any): void {
if (value) {
this.rdSpinner.setValue(value);
}
}

}

最佳答案

当原始微调器的值更改其值时,您应该调用 _onchange 方法。您可以通过订阅原始组件的 valueChanges 并在发出新值时调用 this._onChange() 来实现此目的。

我通过添加修复了该示例

this.rdSpinner.valueChanges.subscribe(result => this._onChange(result));

作为当前 ngOnInit() 中的最后一行。

新的堆栈 Blitz :stackBlitz

关于angular - 自定义组件值未使用 Angular Reactive Form 进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54824595/

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