import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { BaseComponent } from '../../../base.component'; import { Motion } from '../../../shared/models/motions/motion'; import { Category } from '../../../shared/models/motions/category'; import { FormGroup, FormBuilder } from '@angular/forms'; import { MatExpansionPanel } from '@angular/material'; @Component({ selector: 'app-motion-detail', templateUrl: './motion-detail.component.html', styleUrls: ['./motion-detail.component.scss'] }) export class MotionDetailComponent extends BaseComponent implements OnInit { @ViewChild('metaInfoPanel') metaInfoPanel: MatExpansionPanel; @ViewChild('contentPanel') contentPanel: MatExpansionPanel; motion: Motion; metaInfoForm: FormGroup; contentForm: FormGroup; editMotion = false; constructor(private route: ActivatedRoute, private formBuilder: FormBuilder) { super(); this.createForm(); this.route.params.subscribe(params => { // has the motion of the DataStore was initialized before. this.motion = this.DS.get(Motion, params.id) as Motion; // Observe motion to get the motion in the parameter and also get the changes this.DS.getObservable().subscribe(newModel => { if (newModel instanceof Motion) { if (newModel.id === +params.id) { this.motion = newModel as Motion; } } }); }); } /** Parches the Form with content from the dataStore */ patchForm() { this.metaInfoForm.patchValue({ category_id: this.motion.category.id, state_id: this.motion.state.id, recommendation_id: this.motion.recommendation.id, identifier: this.motion.identifier, origin: this.motion.origin }); this.contentForm.patchValue({ currentTitle: this.motion.currentTitle, currentText: this.motion.currentText, currentReason: this.motion.currentReason }); } /** Create the whole Form with empty or default values */ createForm() { this.metaInfoForm = this.formBuilder.group({ identifier: [''], category_id: [''], state_id: [''], recommendation_id: [''], origin: [''] }); this.contentForm = this.formBuilder.group({ currentTitle: [''], currentText: [''], currentReason: [''] }); } saveMotion() { const newMotionValues = { ...this.metaInfoForm.value, ...this.contentForm.value }; this.motion.patchValues(newMotionValues); } getMotionCategories(): Category[] { const categories = this.DS.get(Category); return categories as Category[]; } editMotionButton() { this.editMotion ? (this.editMotion = false) : (this.editMotion = true); if (this.editMotion) { // switch to edit mode this.patchForm(); this.metaInfoPanel.open(); this.contentPanel.open(); } else { // save button this.saveMotion(); } } ngOnInit() { console.log('(init)the motion: ', this.motion); console.log('motion state name: ', this.motion.state); } downloadSingleMotionButton() { console.log('Download this motion'); } }