Angular components | | Search notebook service | Search

This code defines an Angular component for a search bar, including its template, styling, search functionality, and routing configuration, along with a module to encapsulate and share it.

Run example

npm run import -- "Display search notebook component"

Display search notebook component

import {Component, ModuleWithProviders, NgModule} from '@angular/core';
import {COMMON_MODULES} from '../../../imports/core.module';
import {RouterModule, Routes} from '@angular/router';
import {SearchService} from '../../../imports/search.service';

@Component({
    selector: 'bc-search',
    template: `
        <form>
            <md-input-container>
                <input mdInput name="search" required type="text"
                       placeholder="Search"
                       maxlength="100" [(ngModel)]="query" (change)="search()">
            </md-input-container>
        </form>
    `,
    styles: [`
        md-input-container {
            width: 100%;
        }
    `]
})
export class SearchComponent {
    query = '';
    service: SearchService

    constructor(public) {}

    search(): void {
        this.service.search(this.query).subscribe(r => {
            console.log('searched ' + r);
        });
    }
}

export const COMPONENTS = [
    SearchComponent
];

export const authRoutes: Routes = [
    {
        path: '',
        component: SearchComponent,
        data: {roles: ['anonymous', 'user']}
    }
];
export const routing: ModuleWithProviders = RouterModule.forChild(authRoutes);

@NgModule({
    imports: [
        ...COMMON_MODULES,
        routing
    ],
    declarations: COMPONENTS,
    exports: COMPONENTS
})
export class SearchModule {
}

What the code could have been:

// Search Service
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class SearchService {
    // Use a BehaviorSubject to handle search result
    private searchResults: BehaviorSubject = new BehaviorSubject(null);

    search(query: string): Observable {
        // Mock API call, replace with actual API
        return new Observable((observer) => {
            setTimeout(() => {
                observer.next({ results: 'Mock search results' });
                observer.complete();
            }, 1000);
        });
    }

    getSearchResults(): Observable {
        return this.searchResults.asObservable();
    }

    setSearchResults(results: any): void {
        this.searchResults.next(results);
    }
}

// Search Component
import { Component, ElementRef, HostListener } from '@angular/core';
import { SearchService } from './search.service';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';

@Component({
    selector: 'bc-search',
    templateUrl: './search.component.html',
    styleUrls: ['./search.component.css']
})
export class SearchComponent {
    query = '';
    private destroy$: Subject = new Subject();
    service: SearchService;

    constructor(private elementRef: ElementRef, service: SearchService) {
        this.service = service;
    }

    @HostListener('window:beforeunload', ['$event'])
    beforeUnloadHandler(event: any): void {
        this.destroy$.next();
        this.destroy$.complete();
    }

    search(): void {
        this.service.search(this.query).pipe(takeUntil(this.destroy$)).subscribe((results) => {
            console.log('searched'+ results);
            this.service.setSearchResults(results);
        });
    }

    ngOnDestroy(): void {
        this.destroy$.next();
        this.destroy$.complete();
    }
}

// Search Module
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';
import { SearchComponent } from './search.component';
import { SearchService } from './search.service';

const authRoutes: Routes = [
    {
        path: '',
        component: SearchComponent,
        data: { roles: ['anonymous', 'user'] }
    }
];

@NgModule({
    imports: [
        CommonModule,
        RouterModule.forChild(authRoutes)
    ],
    declarations: [SearchComponent],
    providers: [SearchService],
    exports: [SearchComponent]
})
export class SearchModule { }

This code defines an Angular component for a search bar and its associated module.

Here's a breakdown:

  1. Imports:

  2. SearchComponent:

  3. Routing:

  4. SearchModule:

In essence, this code defines a reusable Angular component for a search bar, including its template, styles, logic, and routing configuration.