Search code examples
angulartypescriptangular6angular-services

To pass selected dropdown id to another component


I have an component called list where i am displaying all my customers names in the dropdown as shown below:

enter image description here

Now on clicking/selecting particular item(i,e customer) from the dropdown i want to emit that id to the method/function present in the another component called display.

display component code:

TS file

import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contacts.service';

@Component({
  selector: 'app-display',
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.css']
})
export class DisplayComponent implements OnInit {
public contacts:any;
  constructor(private myService: ContactService) { }

public async ngOnInit(): Promise<void> {
 this.contacts = await this.myService.getCustomersById('id');<=== Need to pass emitted customer id to here
}

}
  • Now i am emitting the ID from the list component's dropdown.

  • But i am unable to pass the emitted id to services file, and i am unable subscribe that id in display component.I have already created a services file. But i am unable to communicate using services file.

DEMO


Solution

  • Changed your on click event from (onSelectionChange) to (click).

    HTML Code:

    <div class="main-div">
    <h3>List</h3>
    <mat-form-field>
      <mat-select placeholder="Select Customer">
        <mat-option *ngFor="let customer of customers" [value]="customer.id" (click)="selected($event, customer.id)">
          {{customer.customerName}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    </div> 
    

    TS Code:

    public async selected(event: MatOptionSelectionChange, id: string): Promise<void> {
        this.myService.onCustomerSelect.next(id);
    }
    

    Service.ts:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { ICustomer } from './models';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable()
    export class ContactService {
     private  baseUrl : string = '../../assets/customers.json';
    
     onCustomerSelect: BehaviorSubject<any> = new BehaviorSubject<any>(null);
      constructor(private http: HttpClient) { }
    
    
     public getCustomers(id : string): Promise<ICustomer> {
      const apiUrl: string = '../../assets/customers.json';
    
      return this.http.get<ICustomer>(apiUrl + id).toPromise();
    }
    
    public async getCustomersById(id : string): Promise<ICustomer[]> {
        const apiUrl: string = `${this.baseUrl}/${id}`;
    
        return this.http.get<ICustomer[]>(apiUrl).toPromise();
      }
    
    }
    

    UPDATED STACKBLITZ

    EDIT:

    you can call API like this:

    public async ngOnInit(): Promise<void> {
        this.myService.onCustomerSelect.subscribe(value => {
          console.log('FROM Display Comp -----', value);
          this.CustId = value;
          if (this.CustId) {
            this.myService.getCustomersById(this.CustId).then(response =>{
              console.log(response)
            })
          }
        })
      }