import { Component, OnInit, ViewChild } from '@angular/core'; import { NgForm } from '@angular/forms'; import { Router } from '@angular/router'; import { AddcategoryService } from './addcategory.service'; @Component({ selector: 'app-addcategory', templateUrl: './addcategory.component.html', styleUrls: ['./addcategory.component.css'] }) export class AddcategoryComponent implements OnInit { @ViewChild('addcategoryform', { static: true }) form: NgForm; uploadedFiles: Array = []; showMessage = false; text = ''; constructor( private router: Router, private addcategoryService: AddcategoryService, ) { } ngOnInit() { } fileChange(element) { this.uploadedFiles = element.target.files; } onAccept() { if (this.form.valid) { this.showMessage = false; const name = this.form.value.title; const subname = this.form.value.subtitle; this.addcategoryService.addCategory(name, subname) .subscribe(data => { const aux: any = data; if (aux.resp) { if (this.uploadedFiles.length > 0) { let formData = new FormData(); for ( let i = 0; i < this.uploadedFiles.length; i++) { formData.append('uploads[]', this.uploadedFiles[i], this.uploadedFiles[i].name); } const extension = this.uploadedFiles[0].name.substring(this.uploadedFiles[0].name.length - 3).toLowerCase(); if (extension !== 'jpg' && extension !== 'png') { this.showMessage = true; this.text = 'Solo imagenes JPG o PNG'; } else { this.showMessage = false; this.addcategoryService.updatePicture(name, formData) .subscribe(() => { this.router.navigateByUrl('/main/category'); }); } } else { this.router.navigateByUrl('/main/category'); } } else { this.showMessage = true; this.text = "Una categoria con ese titulo existe"; } }); } else { this.showMessage = true; this.text = "Titulo y sub titulo no pueden estar vacios"; } } onCancel() { this.router.navigateByUrl('/main/category'); } }