Angular 9 Error 'length' of Undefined

Asked

Viewed 56 times

-1

Good morning! I am doing a function for each click of the user on a given button appear the field for him to add another phone. Follows image below:

inserir a descrição da imagem aqui

This is the html snippet:

            <div *ngFor="let phone of s.controls; let i = index" class="list-group list-group-flush">
               <h3>Complementar Telefone</h3>
             <div [formGroup]="phon" class="row">
              <div class="col-12 col-sm-6 form-group">
                <label class="form-label" for="phone">Celular <span class="text-danger">*</span> </label>
                <input mask="(00) 00000-0000"  formControlName="phone" type="text" class="form-control" id="celular" placeholder="">
                </div>
              </div>
              </div>
   
            <div class="d-flex justify-content-middle">
              <button (click)="onChangePhone()" class="ml-auto mr-auto btn btn-outline-info pt-2 pb-2 btn-sm mb-2" type="button"> + Adicionar Telefone </button>
            </div>
             </form> 

This is the comm section:

  
  public basicInfo: FormGroup;
 
  }

  this.basicInfo = this.formBuilder.group({
      
      phone: [this.currentUser.user.phone, Validators.required],
    });


  get s() { return this.basicInfo.controls; }
  get p() { return this.s.phones as FormArray; }

ngOnInit() {}

 setBasicInfo(basicInfo) {
    this.basicInfo.patchValue({
      numberOfPhones: basicInfo.length
    })
    basicInfo.forEach(element => {
      this.p.push(this.formBuilder.group({
        phone: element.phone,
        
      }));
    });
  }

   onChangePhone(){
    //return console.log('Testando')
    const numberOfPhones = this.basicInfo.value.numberOfPhones;
    this.basicInfo.patchValue({
      numberOfPhones: numberOfPhones + 1
    })

    if (this.p.length < numberOfPhones) {
      for (let i = this.p.length; i < numberOfPhones; i++) {
        this.p.push(this.formBuilder.group({
          phone: ['', Validators.required],
         
        }));
      }
    } else {
      for (let i = this.p.length; i >= numberOfPhones; i--) {
        this.p.removeAt(i);
      }
    }
   
  }

When I click the Add Phone button the following error appears:

inserir a descrição da imagem aqui

Can someone please get me?

  • you have to use formArray inves of the group

  • You refer to yourself in html?

1 answer

1

1 - Create a variable in your system:

phones: FormArray;

2 - Place your div inside another one like this:

<div  formArrayName="phones" >
    <div *ngFor="let phone of s.controls; let i:index">
    //...
    </div>
</div>

3 - Add formGroupName to your index in your div:

<div *ngFor="let phone of s.controls; let i:index"  [formGroupName]="i">

4 - You need to declare your form phones as an array:

  this.basicInfo = this.formBuilder.group({
      phones: this.formBuilder.array([]),
    });

5 - Remove this formGroup, no need:

<div [formGroup]="phon" class="row">

6 - Create a function to start your added phones within each array with validations:

initPhone(): FormGroup {
    return this.formBuilder.group({
        phone: this.formBuilder.control('',[Validators.required]),
    });
}

7 - Modify your add phone function to:

addPhone(){
    this.phones.push(this.initPhone());
}

8 - Create a function to remove the added phones:

removePhone(index:number){
    this.phones = this.basicInfo.get('phones') as FormArray;
    this.phones.removeAt(index);
}

9 - Include an anchor in your html to remove added phones:

<a  (click)="removePhone(i)"><i class="fa fa-times"></i> Excluir</a>

10 - And if it’s an edit page, to insert the phones (from an ajax, for example) just do so:

this.phones = this.form.get('phones') as FormArray;
this.phones.removeAt(0); // Só para garantir que não veio populado com o array vazio.
for (let i = 0; i <= (ajaxData.phones.length-1); i++) {
    this.phones.push(this.initPhone());
    this.phones.at(i).patchValue({
        phone: ajaxData.phones[i].phone, // preencha de acordo com sua variável.
    })
}

Hope I helped, hugs!

  • Oh my brother helped and very much!! now I need to see a way to save this in the bank. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.