html - 重置 Angular react 形式不会更新选择选项

标签 html angular angular-reactive-forms

我使用 materialize-css 创建了一个 Angular 形式.这是 HTML

<form [formGroup]="addFeedForm" (ngSubmit)="addFeed(addFeedForm.value)" class="col s12">
    <div class="row">
        <div class="input-field col m6 s12">
            <select formControlName="departmentId" #feedDepartment>
                <option value=0>General</option>
                <option [value]="department.id" *ngFor="let department of departmentList">{{department.name}}</option>
            </select>
            <label>Department</label>
        </div>

        <div>
            <button type="button" class="btn waves-effect waves-light col s3 offset-s5" (click)="resetAddFeedForm()">Reset</button>

            <button type="submit" [disabled]="!addFeedForm.valid" class="btn waves-effect waves-light col s3 offset-s1">Add</button>

        </div>
    </div>
</form>

这就是我创建 Angular 形式的方式

this.addFeedForm = new FormGroup({
      departmentId: new FormControl(0,Validators.compose([Validators.required])),
});

当我提交时我会提交

addFeed(data: any): void {
    console.log(data);

    this.addFeedForm.reset({    departmentId: 0    });
}

如果我将部门选择选项更改为其他内容并通过将 departmentId 设置为 0 来提交和重置表单,则应在选择选项中选择“General” .

它不是在 UI 上更新,而是在控制台上,它将 departmentId 设置为 0。

UI 行为就像 enter image description here

在 UI 上选择的选项不同但在控制台上 departmentId 是 0

更新:这是 stackblitz

https://stackblitz.com/edit/angular-tchftw

最佳答案

使用

更新您的表单控件
 addFeed(data: any): void {
     console.log(data);
     this.addFeedForm.patchValue({departmentId: '0'});
 }

或者你也可以使用

this.addFeedForm.controls['departmentId'].setValue('0');

关于html - 重置 Angular react 形式不会更新选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54213558/

相关文章:

angular - 如何在 Angular 9 Reactive Form 中获取嵌套的 FormArray 控件

javascript - 按类别悬停表格中的列

jquery - CSS3 渐变 jQuery slider

python - Django Rest Framework 和 Angular 2 文件上传

javascript - 在回调中输入事件的正确方法

javascript - 如何根据下拉选择更改表单验证模式?

Angular 6 - 响应式(Reactive)表单验证模式不起作用

angular - 如何修复 Argument of type '"email "' is not assignable to parameter of type ' string[]' 错误?

javascript - 如何在不影响列表内容字体大小的情况下将字体大小属性应用于 ul 标记

html - 标题菜单 "About Us"中的悬停效果始终在我的主页上触发