import { Component } from '@angular/core'; import { NavbarComponent } from '../navbar/navbar.component'; import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; import { LinkService } from '../service/link.service'; import { Router } from '@angular/router'; import { MatCardModule } from '@angular/material/card'; import { MatInputModule, MatLabel } from '@angular/material/input'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatButtonModule } from '@angular/material/button'; import { debounceTime } from 'rxjs'; @Component({ selector: 'app-create-link', imports: [NavbarComponent, ReactiveFormsModule, MatCardModule, MatFormFieldModule, MatInputModule, MatButtonModule], templateUrl: './create-link.component.html', styleUrl: './create-link.component.css' }) export class CreateLinkComponent { public createLinkForm!: FormGroup; public requestFailed: boolean = false; public errorMessages: Record = {}; constructor(private linkService: LinkService, private router: Router) { } private validationErrorMessages: Record = { required: "This field is required", pattern: "This must be a valid url", }; updateErrorMessages(): void { this.errorMessages = {}; Object.keys(this.createLinkForm.controls).forEach(field => { const control = this.createLinkForm.get(field); if (control && control.errors) { this.errorMessages[field] = Object.keys(control.errors) .map(errorKey => this.validationErrorMessages[errorKey] || `Unknown error: ${errorKey}`) .join(' '); } }); } back() { this.router.navigate(['dashboard']); } ngOnInit(): void { this.createLinkForm = new FormGroup({ name: new FormControl('', Validators.required), link: new FormControl('', [Validators.required, Validators.pattern(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/)]), }); this.createLinkForm.valueChanges.subscribe(() => { this.updateErrorMessages(); }); } submit() { if (!this.createLinkForm.valid) { return; } this.requestFailed = false; this.linkService.createLink({ name: this.createLinkForm.get('name')?.value, link: this.createLinkForm.get('link')?.value, }).catch(() => this.requestFailed = true).finally(() => { if (!this.requestFailed) { this.router.navigate(['dashboard']); } }); } }