exercises

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

search.component.ts (1425B)


      1 import { CommonModule } from '@angular/common';
      2 import { Component, input, output, signal, effect } from '@angular/core';
      3 import { ReactiveFormsModule, FormGroup, FormControl, Validators } from '@angular/forms';
      4 
      5 @Component({
      6   selector: 'section.search',
      7   templateUrl: './search.component.html',
      8   styleUrls: ['./search.component.scss'],
      9   standalone: true,
     10   imports: [CommonModule, ReactiveFormsModule],
     11 })
     12 export class SearchComponent {
     13   // Input for controlling search state from parent (when parent wants to reset)
     14   readonly searching = input<boolean>(false);
     15 
     16   // Internal searching state
     17   readonly isSearching = signal<boolean>(false);
     18 
     19   // Event emitter for search value changes (emitted on form submit)
     20   searchValueChange = output<string>();
     21 
     22   // Reactive form group
     23   searchForm = new FormGroup({
     24     search: new FormControl('', [Validators.minLength(2)]),
     25   });
     26 
     27   constructor() {
     28     // Effect to watch for reset signal from parent
     29     effect(() => {
     30       if (this.searching()) {
     31         this.isSearching.set(false);
     32       }
     33     });
     34   }
     35 
     36   onSearchSubmit(): void {
     37     const searchTerm = this.searchForm.get('search')?.value?.trim();
     38     if (this.searchForm.invalid || !searchTerm) {
     39       return;
     40     }
     41 
     42     // Set searching state to true immediately
     43     this.isSearching.set(true);
     44     // Emit the search value and let parent handle the search logic
     45     this.searchValueChange.emit(searchTerm);
     46   }
     47 }