1
I am creating a code to insert values in an Angular form.
I input these values from the Chrome console... only when I input it that way Angular doesn’t validate the information.
How can I make Angular validate these values so I can click on the send?
Some prints of what I tried to do:
Code (https://stackblitz.com/edit/angular-ivy-z9esrq):
app.componentts.
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
formularioDeUsuario: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.criarFormularioDeUsuario();
}
enviarDados() {
event.preventDefault();
console.log(this.formularioDeUsuario.value);
}
criarFormularioDeUsuario() {
this.formularioDeUsuario = this.fb.group({
nome: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])],
});
}
get nome() {
return this.formularioDeUsuario.get('nome');
}
}
app.component.html
<form [formGroup]="formularioDeUsuario" (ngSubmit)="enviarDados()">
<div>
<label for="nome">Nome: </label>
<input type="text" id="nome" formControlName="nome">
<div *ngIf="!nome.pristine && nome.errors">
<p *ngIf="nome.errors.required">
Nome é obrigatório.
</p>
<p *ngIf="nome.errors.minlength">
Nome deve ter no mínimo 3 caracters.
</p>
<p *ngIf="nome.errors.maxlength">
Nome deve ter no máximo 100 caracters.
</p>
</div>
</div>
<br>
<div>
<button [disabled]="!formularioDeUsuario.valid">Enviar dados</button>
</div>
<br>
<br>
<div>{{ formularioDeUsuario.value | json}}</div>
<div>{{ formularioDeUsuario.valid | json }}</div>
</form>
I appreciate any help!
EDIT:
I tried to use the dispatchEvent, but I couldn’t... maybe I did it wrong. Does anyone know how to solve this problem?