简体   繁体   中英

How can I add items to my FormArray in angular?

I am trying to add some items to my FormArray but I am always get: core.js:6241 ERROR TypeError: Cannot read property 'push' of null.

I can add itens to the test array using my get answersFormArray() , but I am not able to add into the letter and text form array. I tried calling letterFormArray.push(value here) but gives me same error.

       this.userForm = this.fb.group({
      fname: ['', [Validators.required]],
      lname: ['', [Validators.required]],
      email: ['', [Validators.email, Validators.required]],
      facility: ['', [Validators.required]],
      testCode: ['', [Validators.required]],
      date: [''],
      test: this.fb.group({
        name: [''],
        id: [''],
        position: [''],
        scored: [''],
        wrong: [''],
        duration: [''],
/*         answers: this.fb.array([
          this.fb.group({
            num:'',
            letter: this.fb.array([]),
            text: this.fb.array([]),
            userLetter: this.fb.array([]),
            userText: this.fb.array([]),
          })
        ])
      }), */
        answers: this.fb.group({
          user: this.fb.array([
            this.fb.group({
              num:'',
              letter: this.fb.array([]),
              text: this.fb.array([]),
            })
          ]),
          teste: this.fb.array([
            this.fb.group({
              num:'',
              letter: this.fb.array([]),
              text: this.fb.array([]),
            })])
        })
      })
    })

I am trying to add itens to letter and text FormArray.


  get answersFormArray() {
    //return this.userForm.get('test.answers') as FormArray //Option 1
    return this.userForm.get('test.answers.teste') as FormArray
  }

  get letterFormArray() {
    return this.userForm.get('test.answers.teste.letter') as FormArray;
  }
  get textFormArray() {
    return this.userForm.get('test.answers.teste.text') as FormArray;
  }


getTestCorrectAnswers() {
    for(let i = 0; i < this.current_quest.length; i++) {
      const answ = this.fb.group({
        numb: i+1,
        letter: this.fb.array([]),
        text: this.fb.array([])
      })
      for(let z = 0; z < this.current_quest[i].alternatives.length; z++) {
      const alter = this.fb.control("");
        //objective
        if(this.current_quest[i].type === "objective") {
          if(this.current_quest[i].single_or_multi === "single") {
            if(this.current_quest[i].alternatives[z].correct == true) {
              this.textFormArray.push(this.fb.control(this.current_quest[i].alternatives[z].text));
              this.letterFormArray.push(this.fb.control(this.current_quest[i].alternatives[z].letter));
              console.log("Objetiva com uma única alternativa --> " + this.current_quest[i].alternatives[z].text);
            }
          }
          else {
            if(this.current_quest[i].alternatives[z].correct == true) {
              
              console.log("Objetiva com várias alternativas --> " + this.current_quest[i].alternatives[z].text);
            }
          }

        }
        //Subjective
        else {
          if(this.current_quest[i].alternatives.length >= 1) {
            console.log("Subjetiva com chave de resposta --> " + this.current_quest[i].alternatives[z].text);
          }
          else if(!this.current_quest[i].alternatives.length){
            console.log("Subjetiva sem chave de resposta --> ");
          }
        }
        
      }
      this.answersFormArray.push(answ);
    }
  }

This is an example of the object I am creating...

teste: [
        {
          "numb": 1,
          "letter": ["a", "b"],
          "text": ["red", "yellow"]
        },
        {
          "numb": 2,
          "letter": ["a"],
          "text": ["black"]
        }
]

letter and text are FormArray nested into another FormArray. As a FormArray is more basically an array, you need to target the index of the FromGroup populated into it.

get letterFormArray(index: number) {
    return this.userForm.get('test.answers.teste[index].letter') as FormArray;
  }

André, you generally has

get users()
{
  return this.userForm.get('test.answer.users') as FormArray
}
get teste()
{
  return this.userForm.get('test.answer.teste') as FormArray
}

To reach an element of the FormArray you need an "index", and you can not use a getter, see that is getLetter together, NOT get Letter, see also how we use the getters defined before

getLetter(index){
    return this.answer.at(index).letter as FormArray
}
getTest(index){
    return this.answer.at(index).test as FormArray
}

Now you can do

  this.getLetter(index.push(...);
  //and
  this.getTest(index.push(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM