Anuj TBE
Anuj TBE

Reputation: 9790

Angular 6 FormArray discard null fields

I'm using Angular 6. I have a FormArray array like below

contactAddForm: FormGroup;
phone_numbers: FormArray;

ngOnInit() {

  this.contactAddForm = this.formBuilder.group({
    first_name: new FormControl('', [
      Validators.required
    ])
    phone_numbers: this.formBuilder.array([this.createPhoneNumberFormField()])
  });
}

createPhoneNumberFormField(): FormGroup {
  return this.formBuilder.group({
    phone: new FormControl(),
    primary: new FormControl()
  });
}

Here phone is text field while primary is checkbox which sends true or false.

But sometimes adding more fields dynamically and if submitted empty, the values assigned to phone and primary fields are null.

  1. How can I discard formArray field with null phone field from submitting?
  2. How to set primary default to false instead of null?

Upvotes: 1

Views: 1210

Answers (1)

Amit Chigadani
Amit Chigadani

Reputation: 29715

You can set default value to FormControl object, by providing it as the first parameter to its constructor.

createPhoneNumberFormField(): FormGroup {
  return this.formBuilder.group({
    phone: new FormControl(),
    primary: new FormControl(false) // asigning default as false
  });
}

If you want to remove the null fields before submitting them, then you will have to loop through form controls and remove them manually.

Upvotes: 1

Related Questions