在角反应性形式中,为什么HTML选择不明确值?
我正在使用Angular 13反应性形式。
我在每个可重复使用的组件中都有一个简单的方法,可以清除所选择/选择的任何内容的值。它可以与我的输入和自动完成,但不能选择。这是方法和相关的TS:
@Input() parentFormGroup!: FormGroup;
@Input() selectFormControlName!: string;
@Input() selectAbstractControl!: AbstractControl;
@Input() options: string[] = ['Rain', 'Sleet', 'Hail', 'Mist'];
@Input() includeClearButton: boolean = true;
ngOnInit() {
this._setUpForm();
}
ngOnChanges() {}
ngOnDestroy() {
this._removeControl();
}
private _setUpForm() {
this.parentFormGroup.addControl(
this.selectFormControlName,
this.selectAbstractControl
);
}
private _removeControl() {
this.parentFormGroup.removeControl(this.selectFormControlName);
}
clearInput() {
this.selectAbstractControl.patchValue('');
this.selectAbstractControl.updateValueAndValidity();
}
这是HTML:
<select>
<option hidden selected value=""></option>
<option *ngFor="let option of options">{{ option }}</option>
</select>
<button *ngIf="includeClearButton" type="button" (click)="clearInput()">
X
</button>
令人惊讶的是,我在网上没有找到任何答案。足以让我想知道这是否是错字的,因为我不知道为什么PatchValue()和UpdateValueAndVality()可以在输入和自动完成,但不能选择。
我这里有什么想法吗?
I am using Angular 13 Reactive Forms.
I have a simple method in each reusable component that clears the value of whatever has been selected/chosen. It works with my input and autocomplete, but not select. Here is the method and relevant ts:
@Input() parentFormGroup!: FormGroup;
@Input() selectFormControlName!: string;
@Input() selectAbstractControl!: AbstractControl;
@Input() options: string[] = ['Rain', 'Sleet', 'Hail', 'Mist'];
@Input() includeClearButton: boolean = true;
ngOnInit() {
this._setUpForm();
}
ngOnChanges() {}
ngOnDestroy() {
this._removeControl();
}
private _setUpForm() {
this.parentFormGroup.addControl(
this.selectFormControlName,
this.selectAbstractControl
);
}
private _removeControl() {
this.parentFormGroup.removeControl(this.selectFormControlName);
}
clearInput() {
this.selectAbstractControl.patchValue('');
this.selectAbstractControl.updateValueAndValidity();
}
and here is the html:
<select>
<option hidden selected value=""></option>
<option *ngFor="let option of options">{{ option }}</option>
</select>
<button *ngIf="includeClearButton" type="button" (click)="clearInput()">
X
</button>
Surprisingly, I haven't found any answers online. Enough so that I wondered for a while if it was a typo on my part, because I don't know why patchValue() and updateValueAndValidity() would work on input and autocomplete, but not selects.
Any ideas where I have gone wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现了。
这是因为我忘了将[formgroup] =“ parentformgroup”添加到父div,而[formControlname] =“ selectformcontrolname”中的选择元素本身。
I figured it out.
It's because I forgot to add [formGroup]="parentFormGroup" to the parent div and [formControlName]="selectFormControlName" to the select element itself.