can not assign to property "validator" on "selectAnimal": not an object "

0

I'm trying to apply a mandatory validator when filling a select, but I'm getting:

  

can not assign to property "validator" on "selectAnimal": not an object "

Follow 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 set my selectAnimal to be a string? I still do not fully understand how formgroup / formcontrol works.

I need to create a selectAnimal variable of type string?

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

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

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

But I get:

  

"can not assign to property" validator "on" formControlAnimalSelect ":   not an object "

    
asked by anonymous 10.11.2018 / 14:06

1 answer

0

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

These are implementations of Reactive Forms which is a way to work with forms without 'filling' the template, since everything is in the class of your component.

As you are using FormBuilder, it already generates FormControls for you, so your first example only needs the initial value of the control inside the array, as follows:

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