Created
January 17, 2025 17:02
-
-
Save gilvam/342c929e75112b41ef9156992490ee5c to your computer and use it in GitHub Desktop.
Form reativo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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