1

I'm following a YouTube video to learn Angular (this one, around 2h 52m).
These courses are 4 years old (2018), and I'm attempting to apply them on an Angular 12.

Currently I have to add some controls to a FormArray, on a reactive form.

  ngOnInit(): void {
    this.initForm();
  }

  initForm(): void {
    this.userForm = this.formBuilder.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      email: ['', Validators.required, Validators.email],
      drinkPreference: ['', Validators.required],
      hobbies: [this.formBuilder.array([])]
    });
  }

  getHobbies(): FormArray {
    return this.userForm.get('hobbies') as FormArray;
  }

  onAddNewHobby(): void {
    const nouvelHobby: FormControl = this.formBuilder.control('', Validators.required);
    this.getHobbies().push(nouvelHobby);
  }

the onAddNewHobby method is the (click) target for a button.

<button type="button" class="btn btn-success" (click)="onAddNewHobby()">Ajouter un hobby</button>

But when I click on my button (that is inside divs, in an HTML page, etc.)

I am receiving an error:

ERROR TypeError: this.getHobbies().push is not a function

But as far as I can see, everything should be working...

enter image description here

What am I in front of?

1 Answer 1

4

In line:

hobbies: [this.formBuilder.array([])]

... remove brackets, like this:

hobbies: this.formBuilder.array([])
Sign up to request clarification or add additional context in comments.

1 Comment

ok but just WHY?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.