我正在运行 Angular 11 应用程序。在该页面中,我有 2 个单选按钮和 1 个下拉菜单。行为是,每当我更改单选按钮选择时,我想重置下拉值并在下拉列表中显示空值。
下面的代码在 Chrome 中运行良好。但在 IE 中我仍然可以在下拉列表中看到空选项。我不想在下拉列表中显示空选项。
test.component.html
<form [formGroup]="myForm">
<select [id]="control.Id" [formControlName]="control.Id" [value]="control.Value">
<ng-container *ngFor="let item of control.Items">
<option [value]="item.Value">{{item.Key}}</option>
</ng-container>
<option hidden disabled value="" style="display:none;"></option>
</select>
</form>
测试.component.ts
this.myForm.controls['City'].valueChanges.subscribe(this.onCityChange.bind(this));
onCityChange()
{
this.myForm.get['City'].patchValue('');
}
我没有尝试加入
Internet Explorer
,因为它尚未安装,但检查了Edge
,它工作正常!
删除
[value]
绑定,因为您可以在表单控件本身上设置默认值,所以这里不需要 value
这行
this.myForm.get['City'].patchValue('');
似乎是无效语法,我们可以重写它!
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { ReactiveFormsModule, FormGroup, FormControl } from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, ReactiveFormsModule],
template: `
<form [formGroup]="myForm">
<select [id]="control.Id" [formControlName]="control.Id">
<ng-container *ngFor="let item of control.Items">
<option [value]="item.Value">{{item.Key}}</option>
</ng-container>
<option hidden disabled value="" style="display:none;"></option>
</select>
</form>
<button (click)="clear()">clear</button>
`,
})
export class App {
name = 'Angular';
myForm = new FormGroup({
test: new FormControl('One'),
});
control = {
Id: 'test',
Value: 'test',
Items: [
{ Key: '1', Value: 'One' },
{ Key: '2', Value: 'Two' },
{ Key: '3', Value: 'Three' },
],
};
clear() {
this.myForm?.get('test')?.patchValue('');
}
}
bootstrapApplication(App);