import { Component , OnInit } from '@angular/core' ; import { FormControl , FormGroup , Validators } from '@angular/forms' ; import { Subscription } from 'rxjs' ; import { CompassService } from '../compass.service' ; @ Component ( { selector : 'm-compassForm' , templateUrl : './form.component.html' , styleUrls : [ './form.component.ng.scss' ] , } ) export class CompassFormComponent implements OnInit { private subscriptions : Subscription [ ] = [ ] ; init : boolean = false ; questions : any ; form ; constructor ( public compassService ) { } ngOnInit ( ) { this . subscriptions . push ( this . compassService . questions$ . subscribe ( questions => { if ( ! questions || ! questions . length ) { this . compassService . fetchQuestions ( ) ; } else { this . questions = questions ; this . setupForm ( ) ; } } ) ) ; this . subscriptions . push ( this . compassService . submitRequested$ . subscribe ( requested => { if ( requested ) { this . submit ( ) ; } } ) ) ; } setupForm ( ) { const controls = { } ; this . questions . forEach ( q => { controls [ q . questionId ] = new FormControl ( q . currentValue , { validators : [ Validators . min ( q . minimumRangeValue ) , Validators . max ( q . maximumRangeValue ) , ] , } ) ; } ) ; this . form = new FormGroup ( controls ) ; this . init = true ; } setAnswers ( ) { const answers = { } ; this . questions . forEach ( q => { answers [ q . questionId ] = this . form . get ( q . questionId ) . value ; } ) ; this . compassService . answers$ . next ( answers ) ; } async submit ( ) { if ( this . canSubmit ( ) ) { this . setAnswers ( ) ; await this . compassService . saveAnswers ( ) ; } } canSubmit ( ) { return this . form . valid && ! this . form . pristine ; } ngOnDestroy ( ) { for ( let subscription of this . subscriptions ) { subscription . unsubscribe ( ) ; } } }