11import { Component , OnInit } from '@angular/core' ;
2- import { FormBuilder , FormGroup } from '@angular/forms' ;
2+ import { FormArray , FormBuilder , FormGroup , Validators } from '@angular/forms' ;
33import { UserService } from '../services/user.service' ;
44import { Router } from '@angular/router' ;
55import { User } from '../models/User.model' ;
@@ -24,10 +24,11 @@ export class NewUserComponent implements OnInit {
2424
2525 initForm ( ) {
2626 this . userForm = this . formBuilder . group ( {
27- firstName : '' ,
28- lastName : '' ,
29- email : '' ,
30- drinkPreference : ''
27+ firstName : [ '' , Validators . required ] ,
28+ lastName : [ '' , Validators . required ] ,
29+ email : [ '' , [ Validators . required , Validators . email ] ] ,
30+ drinkPreference : [ '' , Validators . required ] ,
31+ hobbies : this . formBuilder . array ( [ ] )
3132 } ) ;
3233 }
3334
@@ -37,9 +38,23 @@ export class NewUserComponent implements OnInit {
3738 formValue [ 'firstName' ] ,
3839 formValue [ 'lastName' ] ,
3940 formValue [ 'email' ] ,
40- formValue [ 'drinkPreference' ]
41+ formValue [ 'drinkPreference' ] ,
42+ formValue [ 'hobbies' ] ? formValue [ 'hobbies' ] : [ ]
4143 ) ;
4244 this . userService . addUser ( newUser ) ;
4345 this . router . navigate ( [ '/users' ] ) ;
4446 }
47+
48+ getHobbies ( ) : FormArray {
49+ return this . userForm . get ( 'hobbies' ) as FormArray ;
50+ }
51+
52+ onAddHobby ( ) {
53+ const newHobbyControl = this . formBuilder . control ( null , Validators . required ) ;
54+ this . getHobbies ( ) . push ( newHobbyControl ) ;
55+ }
56+
57+ onRemoveHobby ( ) {
58+ this . getHobbies ( ) . removeAt ( - 1 ) ;
59+ }
4560}
0 commit comments