import { City } from './../../models/city' ; import { Place } from './../../models/place' ; import { TripService } from './../../services/trips.service' ; import { Router , ActivatedRoute } from '@angular/router' ; import { Trip } from '../../models/trip' ; import { Observable } from 'rxjs/Observable' ; import { Form , FormGroup , FormBuilder , FormArray , Validators , FormControl } from '@angular/forms' ; import { Component , OnInit , EventEmitter } from '@angular/core' ; @ Component ( { selector : 'trip-edit' , templateUrl : './trip-edit.component.html' , styleUrls : [ './trip-edit.component.css' ] } ) export class TripEditComponent { trip : Trip ; tripForm : FormGroup ; editingStatus : boolean = false ; constructor ( private fb , private activatedRoute , private trips ) { if ( 'id' in this . activatedRoute . snapshot . params ) { this . editingStatus = true ; } } ngOnInit ( ) { if ( this . editingStatus ) { this . trip = this . trips . getTrip ( ) ; this . initForm ( this . trip ) ; } else { this . initForm ( ) ; } } method onSubmit ( ) { if ( this . tripForm . valid ) { console . log ( 'trip form is valid' ) ; } } method initForm ( trip ? ) { let name ; if ( trip ) { name = trip . name ; } else { name = '' ; } let cities = new FormArray ( [ ] ) ; let places = new FormArray ( [ ] ) ; this . tripForm = new FormGroup ( { name : new FormControl ( '' , Validators . required ) , cities : cities } ) ; if ( ! trip ) { this . addCity ( ) ; this . addPlace ( 0 ) ; } else { trip . cities . forEach ( ( city , cityIndex ) => { this . addCity ( city ) ; city . places . forEach ( ( place , placeIndex ) => { this . addPlace ( cityIndex , place ) ; } ) ; } ) ; } } method param void return addCity ( city ? ) { let places = new FormArray ( [ ] ) ; let name = city ? city . name : '' ; ( < FormArray > this . tripForm . controls [ 'cities' ] ) . push ( new FormGroup ( { name : new FormControl ( name , Validators . required ) , places : places } ) ) ; } method param { cityIndex } index return { void } addPlace ( cityIndex , place ? ) { let name = place ? place . name : '' ; ( < FormArray > ( < FormGroup > ( < FormArray > this . tripForm . controls [ 'cities' ] ) . controls [ cityIndex ] ) . controls [ 'places' ] ) . push ( new FormGroup ( { name : new FormControl ( name , Validators . required ) , } ) ) ; } }