can’t assign to Property "Validator" on "selectAnimal": not an Object"

Asked

Viewed 143 times

0

I’m trying to apply a mandatory Validator when filling a select, but I’m getting:

can’t assign to Property "Validator" on "selectAnimal": not an Object"

Follows my code:

ngOnInit() {
    this.firstFormGroup = this._formBuilder.group({
        firstCtrl: ['', Validators.required]
      });
      this.secondFormGroup = this._formBuilder.group({
        selectAnimal:[Validators.required]
      });

My template:

 <form [formGroup]="secondFormGroup">
<div class="formSegundoGrupo">
                <mat-form-field>
                  <mat-select name="selectAnimals" formControl="selectAnimal" placeholder="Eu perdi um...">
                    <mat-option value="gato">
                      Gato
                    </mat-option>
                    <mat-option value="cahorro">
                      Cachorro
                    </mat-option>
                    <mat-option value="coelho">
                      Coelho
                    </mat-option>
                    <mat-option value="tartaruga">
                      Tartaruga
                    </mat-option>
                  </mat-select>

                  <mat-error *ngIf="selectAnimal.hasError('required')">Você precisa selecionar ao menos um pet!</mat-error>

                </mat-form-field>
             </div>

How do I define that my selectAnimal should be a string? I still don’t fully understand how formgroup/formcontrol works.

I need to create a string type selectAnimal variable?

@Edit: I tried at the beginning of the variables declaration:

formControlAnimalSelect = new FormControl('valid', [
  Validators.required,
  Validators.pattern('valid'),
]);

ngOnInit() {
      this.secondFormGroup = this._formBuilder.group({
        formControlAnimalSelect:['',Validators.required]
      });

But I get:

"can’t assign to Property "Validator" on "formControlAnimalSelect": not an Object"

1 answer

0

Formgroup and Formcontrol are classes used to manage a group of inputs or an input, respectively.

Are implementations of Reactive Forms that is a way to work with forms without 'filling' the template, because everything stays in the class of your component.

Since you are using Formbuilder, it already generates the Formcontrols for you, so your first example only needs the initial value of the control within the array, as follows:

this.secondFormGroup = this._formBuilder.group({
    selectAnimal:['', Validators.required]
});

Browser other questions tagged

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