Advertisement
bebo231312312321

Untitled

Mar 21st, 2024
404
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { CommonModule } from '@angular/common';
  2. import { Component, OnInit } from '@angular/core';
  3. import { FormArray, FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
  4. import { ApiService } from '../services/api.service';
  5. import { AuthenticatedComponent } from '../authenticated/authenticated.component';
  6.  
  7. @Component({
  8.   selector: 'app-create-page',
  9.   templateUrl: './create-page.component.html',
  10.   styleUrls: ['./create-page.component.css'],
  11.   standalone: true,
  12.   imports: [ReactiveFormsModule, CommonModule,AuthenticatedComponent]
  13. })
  14. export class CreatePageComponent implements OnInit {
  15.   createForm!: FormGroup;
  16.   imagePreview: string | ArrayBuffer = '';
  17.   currentFormSection = 1;
  18.   totalFormSections = 4;
  19.   imagesPreview: string[] = [];
  20.   dayImages: { previews: string[] }[] = [];
  21.   currentDayIndex: number = 0;
  22.  
  23.  
  24.   constructor(private fb: FormBuilder, private apiService: ApiService) { }
  25.  
  26.   ngOnInit() {
  27.     this.createForm = this.fb.group({
  28.       image: [null],
  29.       title: ['', Validators.required],
  30.       paragraph: ['', Validators.required],
  31.       "title-desc": ['', Validators.required],
  32.       'info-desc': ['', Validators.required],
  33.       'images': [null],
  34.       dateRange: this.fb.group({
  35.         start: ['', Validators.required],
  36.         end: ['', Validators.required]
  37.       }),
  38.       price: ['', [Validators.required, Validators.pattern(/^\d+$/)]],
  39.       conditions: this.fb.group({
  40.         ticketsIncluded: [false],
  41.         allTransportCosts: [false],
  42.         accommodations: [false],
  43.         allMeals: [false],
  44.         practices: [false],
  45.         atvTour: [false],
  46.         spaAccess: [false],
  47.         guidesIncluded: [false],
  48.         medicalInsurance: [false],
  49.         personalExpenses: [false],
  50.         alcoholicBeverages: [false],
  51.         unspecifiedServices: [false],
  52.         additionalActivitiesFee: [false],
  53.         cancellationInsurance: [false]
  54.       }),
  55.       days: this.fb.array([this.initDayForm()]),
  56.  
  57.     });
  58.     // console.log('fs', this.createForm.value)
  59.   }
  60.  
  61.   initDayForm(): FormGroup {
  62.     return this.fb.group({
  63.       dayImage: [null],
  64.       dayTitle: ['', Validators.required],
  65.       dayInfo: ['', Validators.required]
  66.     });
  67.   };
  68.   goToDay(index: number) {
  69.     this.currentDayIndex = index;
  70.   }
  71.  
  72.  
  73.   nextDay() {
  74.     if (this.currentDayIndex < this.days.length - 1) {
  75.       this.currentDayIndex++;
  76.     }
  77.   }
  78.  
  79.   previousDay() {
  80.     if (this.currentDayIndex > 0) {
  81.       this.currentDayIndex--;
  82.     }
  83.   }
  84.  
  85.   get days(): FormArray {
  86.     return this.createForm.get('days') as FormArray;
  87.   }
  88.  
  89.   onImageChange(event: Event) {
  90.     const file = (event.target as HTMLInputElement).files?.[0];
  91.     if (file) {
  92.       const reader = new FileReader();
  93.       reader.onload = () => {
  94.         this.imagePreview = reader.result!;
  95.       };
  96.       reader.readAsDataURL(file);
  97.     }
  98.   }
  99.   onImagesChange(event: Event) {
  100.     const files = (event.target as HTMLInputElement).files;
  101.     this.imagesPreview = [];
  102.     if (files && files.length <= 4) {
  103.       Array.from(files).forEach(file => {
  104.         const reader = new FileReader();
  105.         reader.onload = () => {
  106.           this.imagesPreview.push(reader.result as string);
  107.         };
  108.         reader.readAsDataURL(file);
  109.       });
  110.     } else {
  111.  
  112.       console.error("Можете да качите максимум 4 снимки.");
  113.     }
  114.   };
  115.  
  116.  
  117.   addDay() {
  118.     const days = this.createForm.get('days') as FormArray;
  119.     days.push(this.initDayForm());
  120.     this.dayImages.push({ previews: [] });
  121.   }
  122.  
  123.   removeDay(index: number) {
  124.     const days = this.createForm.get('days') as FormArray;
  125.     days.removeAt(index);
  126.     this.dayImages.splice(index, 1);
  127.   }
  128.  
  129.   onDayImageChange(event: Event, index: number) {
  130.     const files = (event.target as HTMLInputElement).files;
  131.     if (files) {
  132.       this.dayImages[index] = { previews: [] };
  133.       Array.from(files).forEach(file => {
  134.         const reader = new FileReader();
  135.         reader.onload = () => {
  136.           this.dayImages[index].previews.push(reader.result as string);
  137.         };
  138.         reader.readAsDataURL(file);
  139.       });
  140.     }
  141.   }
  142.   getDayImagesPreviews(index: number): string[] {
  143.     return this.dayImages[index]?.previews ?? [];
  144.   }
  145.  
  146.  
  147.  
  148.  
  149.  
  150.  
  151.  
  152.  
  153.  
  154.   goToNextSection() {
  155.     if (this.currentFormSection < this.totalFormSections) {
  156.       this.currentFormSection++;
  157.     }
  158.  
  159.   }
  160.  
  161.   goToPreviousSection() {
  162.     if (this.currentFormSection > 1) {
  163.       this.currentFormSection--;
  164.     }
  165.  
  166.   }
  167.   onSubmit() {
  168.  
  169.     // prowerki
  170.  
  171.         // console.log('status',this.createForm.status); // Покажете общия статус на формата
  172.     // console.log('formValue',this.createForm.value); // Покажете стойностите на формата
  173.     // console.log('errors',this.createForm.errors); // Покажете грешките на формата, ако има такива
  174.  
  175.     // if (this.createForm.invalid) {
  176.     //   console.log('controles',this.createForm.controls); // Ще покаже статуса на всички контроли
  177.     // }
  178.     // const days = this.createForm.get('days') as FormArray;
  179.     // let isValid = true;
  180.  
  181.     // days.controls.forEach((dayFormGroup, index) => {
  182.     //   if (!dayFormGroup.valid) {
  183.     //     console.log(`Day ${index + 1} is not valid.`);
  184.     //     isValid = false;
  185.     //   }
  186.     // });
  187.  
  188.     // if (!isValid) {
  189.     //   console.log('There are invalid days. Cannot submit.');
  190.     //   return;
  191.     // }
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.     if (this.createForm.valid) {
  199.       const formData = {
  200.         ...this.createForm.value,
  201.         image: this.imagePreview,
  202.         images: this.imagesPreview,
  203.         days: this.days.value.map((day: any, index: number) => {
  204.  
  205.           const dayImageObj = this.dayImages[index];
  206.           return {
  207.             ...day,
  208.             dayImage: dayImageObj ? dayImageObj.previews : []
  209.           };
  210.         })
  211.       };
  212.  
  213.  
  214.       this.apiService.createDestination(formData).subscribe({
  215.         next: (response) => {
  216.           console.log('Destination created successfully', response);
  217.  
  218.         },
  219.         error: (error) => {
  220.           console.error('Error creating destination', error);
  221.  
  222.         }
  223.       });
  224.     } else {
  225.       console.log('Form is not valid');
  226.  
  227.     }
  228.   }
  229.  
  230. }
  231.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement