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 "