import { Location } from '@angular/common'; import { Component, Input, OnInit } from '@angular/core'; import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms'; import { ContactEmailFormModel } from '@app/core/model/contact/contact-email-form-model'; import { ContactSupportService } from '@app/core/services/contact-support/contact-support.service'; import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service'; import { BaseComponent } from '@common/base/base.component'; import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model'; import { TranslateService } from '@ngx-translate/core'; import { takeUntil } from 'rxjs/operators'; @Component({ selector: 'app-contact-content', templateUrl: './contact-content.component.html', styleUrls: ['./contact-content.component.scss'] }) export class ContactContentComponent extends BaseComponent implements OnInit { @Input() isDialog: boolean; @Input() form: FormGroup; private contactEmailFormModel: ContactEmailFormModel; public formGroup: FormGroup; constructor( private contactSupportService: ContactSupportService, private _location: Location, private uiNotificationService: UiNotificationService, private language: TranslateService, ) { super(); } ngOnInit() { if (this.isDialog) { this.formGroup = this.form; } else { this.contactEmailFormModel = new ContactEmailFormModel(); this.formGroup = this.contactEmailFormModel.buildForm(); } } cancel() { this._location.back(); } send() { this.contactSupportService.postEmail(this.formGroup.value) .pipe(takeUntil(this._destroyed)) .subscribe( complete => this.onCallbackSuccess(), error => this.onCallbackError(error) ); this.formGroup.reset(); } onCallbackSuccess(): void { this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-EMAIL-SEND'), SnackBarNotificationLevel.Success); } onCallbackError(errorResponse: any) { this.setErrorModel(errorResponse.error); this.validateAllFormFields(this.formGroup); this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-EMAIL-SEND'), SnackBarNotificationLevel.Error); } public setErrorModel(validationErrorModel: ValidationErrorModel) { Object.keys(validationErrorModel).forEach(item => { (this.contactEmailFormModel.validationErrorModel)[item] = (validationErrorModel)[item]; }); } public validateAllFormFields(formControl: AbstractControl) { if (formControl instanceof FormControl) { formControl.updateValueAndValidity({ emitEvent: false }); } else if (formControl instanceof FormGroup) { Object.keys(formControl.controls).forEach(item => { const control = formControl.get(item); this.validateAllFormFields(control); }); } else if (formControl instanceof FormArray) { formControl.controls.forEach(item => { this.validateAllFormFields(item); }); } } }