【问题标题】:Best way to remove a field from reactive angular form从反应角度形式中删除字段的最佳方法
【发布时间】:2018-08-14 16:46:17
【问题描述】:

当我更新它时,我不想从我的反应式 Angular 6 表单中发送一个字段,因为我正在使用的 API 在更新时不处理这个“额外”字段。

当我添加我的对象时,这就是我发送的内容:

{"person": {"name":"John", "address": "2050 Bamako Place Washington, DC 20521-2050", "code": "256222"}

当我更新我的表单时,我想要(不再有“代码”):

{"person": {"name":"John", "address":"2051 Bamako Place Washington, DC 20521-2051"}

我尝试对我的字段使用“禁用”,但它仍然提交我不想要的字段。我也试过只读但和上面一样。我不知道实现这一目标的最佳方法是什么。

form.html

        <form [formGroup]="testForm" (ngSubmit)="formValidate()" >
            <mat-card-content class="mat-card-content">
                <div fxLayout="row">
                    <div fxLayout="column" fxFlex="100%">

                        <mat-form-field class="form-input"> 
                            <input matInput formControlName="name" required
                            placeholder="Name" /> 
                        </mat-form-field>

                        <mat-form-field class="form-input">
                            <textarea matInput formControlName="address" required
                            placeholder="Address" rows="4" cols="200"></textarea>

                        </mat-form-field>

                        <mat-form-field class="form-input"> 
                            <input matInput formControlName="code" required
                            placeholder="Code" /> 

                        </mat-form-field>

                     </div>
                    </div>
            </mat-card-content>
            <mat-card-footer style="margin:0 auto;">
                <div fxLayout="row" fxLayoutAlign="end center">

                    <button type="submit" color="primary" mat-raised-button [disabled]="testForm.invalid">Submit</button>
                </div>
            </mat-card-footer>
        </form>

form.ts

    this.testForm = fb.group({
        'name': fb.control('', [Validators.required]),
        'address': fb.control('', [Validators.required]),
        'code': fb.control('', [Validators.required]), // I would like to do not send this field when I'm updating my form.
    });


formValidate() {

        this.person = this.testForm.value;
        if (this.updateForm) {
            this.person['id'] = this.currentId;
        }

        console.log(this.person);

       // create or update by sending object to the API
      ...
    }

非常感谢!

【问题讨论】:

    标签: angular angular-reactive-forms


    【解决方案1】:

    试试这个:this.testForm.removeControl('code'); 您还可以创建一个名为 ie 的对象。 request 并将您要发送的值放在那里。

    【讨论】:

    • 它有效 :) 但我检查了我的视图“!testForm.controls['code'].valid”并抛出错误“无法读取未定义的属性'valid'”。
    • 这是因为您删除了该控件,所以它无法检查 null 的有效性。您要么检查testForm.controls['code'] 是否存在,要么使用第二种方法并创建一个自定义对象并将您的值映射到它。
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 2022-01-18
    • 2013-01-16
    • 2022-11-03
    • 2018-12-28
    • 1970-01-01
    • 2018-02-11
    • 2019-05-25
    相关资源
    最近更新 更多