Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set formControl valid when i have at least one element inside?

I have one formGroup that have an array:

createForm() {
   this.form = this.formBuilder.group({
      name: [[], [Validators.required]]      
   })
}

I have a list of checkbox that when it is checked, i add in this array the value, but when i do console.log(form.controls('name').valid) it returns false but i have elements in this formControl:

<mat-list-item *ngFor="let name of myNames">
   <mat-checkbox (click)="addItemInArray(name.id)">{{ name.name }}</mat-checkbox>
</mat-list-item>

addItemInArray(id: number) {
   const indexElem = this.form.get('name').value.indexOf(id);
   if (indexElem === -1) {
      this.form.get('name').value.push(id)
   } else {
      this.form.get('name').value.splice(indexElem, 1)
}

I'm looking if there's a way to make this control valid when i have at least one element inside the array.

like image 718
veroneseComS Avatar asked Jan 30 '26 09:01

veroneseComS


2 Answers

I think you can use Validators.minLength(1). According to the documentation:

Note that the minLength validator is intended to be used only for types that have a numeric length property, such as strings or arrays.

createForm() {
   this.form = this.formBuilder.group({
      name: [[], [Validators.minLength(1)]]      
   })
}

Second thing, you need to use .setValue() to set the value or call .updateValueAndValidity() after appending the value. The validator won't be aware that the array is changed because it is keeping the same object reference. Personally, I will choose the first, because I hate mutable arrays. You can try something like the following:

const control = this.form.get('name');
const control.setValue([...control.value, theNewValue]);
like image 172
Aboodz Avatar answered Jan 31 '26 23:01

Aboodz


Here is the example with the formArray, but I like @Aboodz's answer too.

In Component

get nameArray() {
  return this.form.get('name') as FormArray;  // 
}

createForm() {
   this.form = this.formBuilder.group({
      name: this.formBuilder.array([], [Validators.required])   
   })
}

addItemInArray(id: number) {
   const indexElem = this.findItemIndex(id);
   if (indexElem === -1) {
     this.nameArray.push(this.formBuilder.control(id));
   } else {
     this.nameArray.removeAt(indexElem)
}

findItemIndex(id: number) {
  return this.nameArray.controls.findIndex(control => control.value === id);
}

UPDATE Please check the Stackblitz example: https://angular-forms-formarray-example-uwp9tm.stackblitz.io

I have created the simple example, and add a console where I am printing the FormArray value

like image 36
Ashot Aleqsanyan Avatar answered Jan 31 '26 21:01

Ashot Aleqsanyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!