I am learning angular and having some problems with angular reactive forms.
I want to reset the forms after i read it, but for some reason it clears before console log.
I tried using ngSubmit="onSubmit()" with the button type="reset" but it was the same. For some reason the value is reset but the validators are still touched (After submit, all required fields appear with error)
My code:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
@Component({
selector: 'app-deals',
templateUrl: './deals.component.html',
styleUrls: ['./deals.component.css']
})
export class DealsComponent implements OnInit {
dealsForm!:FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit(): void {
this.dealsForm = this.formBuilder.group(
{'meio': [null, Validators.required],
'mes': [null,[Validators.required],],
'gender': ['male'],
'files':[null]}
);
}
onSubmit(){
console.log(this.dealsForm)
this.dealsForm.reset()
}
}
Html:
<div class="container">
<h1>Upload Deals</h1>
<form [formGroup]="dealsForm">
<div>
<mat-form-field appearance="outline">
<mat-label>Meio</mat-label>
<mat-select formControlName="meio">
<mat-option value="otv"> OTV </mat-option>
<mat-option value="ptv"> PTV </mat-option>
<mat-option value="radio"> Radio </mat-option>
<mat-option value="ooh"> OOH </mat-option>
</mat-select>
<mat-error>Selecione uma opção</mat-error>
</mat-form-field>
</div>
<div>
<mat-form-field appearance="outline">
<mat-label>Mês</mat-label>
<mat-select formControlName="mes">
<mat-option value=1> Janeiro </mat-option>
<mat-option value=2> Fevereiro </mat-option>
<mat-option value=3> Março </mat-option>
<mat-option value=4> Abril </mat-option>
<mat-option value=5> Maio </mat-option>
<mat-option value=6> Junho </mat-option>
<mat-option value=7> Julho </mat-option>
<mat-option value=8> Agosto </mat-option>
<mat-option value=9> Setembro </mat-option>
<mat-option value=10> Outubro </mat-option>
<mat-option value=11> Novembro </mat-option>
<mat-option value=12> Dezembro </mat-option>
</mat-select>
</mat-form-field>
</div>
<div>
<input type="file" formControlName="files">
</div>
<button mat-raised-button
(click)="onSubmit()"
[disabled]='!dealsForm.valid'
>Enviar</button>
</form>
</div>
