import { Component, OnInit, Input } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { BsModalRef } from 'ngx-bootstrap'; import { ToastrService } from 'ngx-toastr'; import { NGXLogger } from 'ngx-logger'; import { ItemCategoryService } from '../../../services/item.category.service'; import { ItemSubCategoryService } from '../../../services/item.subcategory.service'; @Component({ selector: 'app-new-subcategory', templateUrl: './new-subcategory-modal.component.html', styleUrls: ['./new-subcategory-modal.component.css'] }) export class NewSubCategoryComponent implements OnInit { @Input() title; modalRef: BsModalRef; subCategoryForm: FormGroup; productCategories:any[]; isSubCategoryExists: boolean; constructor(private fb: FormBuilder, private toastr: ToastrService, private logger: NGXLogger, public bsModalRef: BsModalRef, private itemCategoryService: ItemCategoryService, private itemSubCategoryService: ItemSubCategoryService) { this.itemCategoryService.getAllItem_Categories().subscribe((result: { status: string, message: string, data }) => { this.productCategories = result.data; }); } ngOnInit(): void { this.subCategoryForm = this.fb.group({ product_category: ['', Validators.required], subcategory_name: ['', Validators.required] }); } async checkForSubCategoryName() { let subCategoryName = this.subCategoryForm.get('subcategory_name').value; const body = await this.itemSubCategoryService.isSubCategoryExists(subCategoryName); this.isSubCategoryExists = body['data'] as boolean; if (this.isSubCategoryExists) { this.subCategoryForm.get('subcategory_name').setValue(''); } } /* @usage: called when a form is submitted */ async onSubmit() { if(this.subCategoryForm.get('product_category').value === '' || this.subCategoryForm.get('subcategory_name').value === ''){ this.subCategoryForm.controls['product_category'].markAllAsTouched(); this.subCategoryForm.controls['subcategory_name'].markAllAsTouched(); } if (this.subCategoryForm.valid){ const newSubCategory: any = {}; newSubCategory.category_code = this.subCategoryForm.controls['product_category'].value; newSubCategory.subcategory_name = this.subCategoryForm.controls['subcategory_name'].value; this.itemSubCategoryService.createNewSubCategory(newSubCategory).subscribe((result: { status: string, message: string, data }) => { if (result.status === 'success') { this.logger.debug('New Sub Category has been created'); this.toastr.success('New Sub Category has been created'); } },(error) => { this.toastr.error('New Sub Category can not be created'); this.logger.error(error); }); this.bsModalRef.hide(); }else{ this.subCategoryForm.controls['product_category'].markAllAsTouched(); this.subCategoryForm.controls['subcategory_name'].markAllAsTouched(); } } get product_category() { return this.subCategoryForm.get('product_category') } get subcategory_name() { return this.subCategoryForm.get('subcategory_name') } }