Skip to content

Instantly share code, notes, and snippets.

@gilvam
Created January 17, 2025 17:02
Show Gist options
  • Select an option

  • Save gilvam/342c929e75112b41ef9156992490ee5c to your computer and use it in GitHub Desktop.

Select an option

Save gilvam/342c929e75112b41ef9156992490ee5c to your computer and use it in GitHub Desktop.
Form reativo
export class FormUser {
constructor(
public name = '',
public email = '',
public age = 0
) {}
get isAdult(): boolean {
return this.age >= 18;
}
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
standalone: true
})
export class AppComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.initializeForm(new FormUser());
}
private initializeForm(user: FormUser): FormGroup {
return this.fb.group({
name: [user.name, Validators.required],
email: [user.email, [Validators.required, Validators.email]],
age: [user.age, Validators.min(0)]
});
}
setForm(user: FormUser): void {
this.form.patchValue(user);
}
getForm(): FormUser {
return this.form.value;
}
resetForm(): void {
this.form.reset(new FormUser());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment