Joe Allen
Joe Allen

Reputation: 1317

Best way to remove a field from reactive angular form

I would like to do not send a field from my reactive Angular 6 form when I'm updating it because the API I'm working with doesn't handle this "extra" field in update.

When I add my object, this is what I send :

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

When I update my form, I would like (no more "code") :

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

I tried to used "disable" for my field but it still submit the field I don't want. I also tried readonly but same as above. I don't know what is the best way to achieve this.

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
      ...
    }

Thank you very much !

Upvotes: 1

Views: 4943

Answers (1)

karoluS
karoluS

Reputation: 3218

Try this: this.testForm.removeControl('code'); You can also create a object called ie. request and put there values you want to send.

Upvotes: 4

Related Questions