Parent dropdown passes selected value to child component for triggering various API calls

Can anyone assist me with sending http requests to service methods based on a dropdown selection using Rxjs Observables in Angular? I am passing the selected value from the dropdown to a child component. Thank you for your help.

child-component.ts

@Input() Type;
private data: any;

constructor(private apiService: ApiService){
switch(this.Type){
  case 't1': this.apiService.getAllByT1(this.Type).subscribe(result =>   {
    this.data = result;
  });
  break;
  case 't2': this.apiService.getAllByT2(this.Type).subscribe(result =>   {
    this.data = result;
  });
  break;
  case 't3': this.apiService.getAllByT3(this.Type).subscribe(result =>   {
    this.data = result;
  })
}

ngOnInit(){
}
parent-component.html

<select [(ngModel)]="Type" class="form-control" (change)='onOptionsSelected($event)'>
<option id="1" value="t1">t1</option>
<option id="2" value="t2">t2</option>
<option id="3" value="t3">t3</option>
</select>

<app-child [Type]="Type" (getAPI)="onOptionsSelected($event)"></app-child>

Answer №1

To effectively process the @Input() Type in Angular, it's important to avoid placing that logic in the constructor. This is because Angular has not yet set up any data bindings at that point. Instead, it's recommended to handle any @Input() variables in either the ngOnInit() or ngOnChanges() lifecycle hooks.

The documentation describes ngOnInit() as "A lifecycle hook that is called after Angular has initialized all data-bound properties of a directive".

For processing changes in data-bound properties, utilizing the ngOnChanges() (documentation link) lifecycle hook would be more appropriate since it is triggered when any data-bound property of a directive changes.

It's advisable to transfer your code from the constructor to the ngOnChanges() method for better handling and responsiveness.

child-component.ts

@Input() type;
private data: any;

constructor(private apiService: ApiService){
}

ngOnInit(){
}

ngOnChanges() {
    if (this.type) {
        switch(this.type) {
            case 't1': 
            this.apiService.getAllByT1(this.type).subscribe(result => {
                this.data = result;
            });
            break;
            case 't2': 
            this.apiService.getAllByT2(this.type).subscribe(result => {
                this.data = result;
            });
            break;
            case 't3': 
            this.apiService.getAllByT3(this.type).subscribe(result => {
                this.data = result;
            });
            break;
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Safari experiencing issues with video player controls not functioning properly

Within my application, there is a div element that contains a video. Clicking on the div triggers an event that navigates to another page. Expectation I expect to be able to play the video and use its controls without triggering the navigation event. Ac ...

The error message "Undefined value received instead of a string or boolean in Vuetify and nuxt.js rules" indicates that the expected data type was not provided

I recently created an app at my workplace and encountered an error in the text area similar to what I have described in my title. After researching the issue online, I found some information but still struggle to fully grasp the concept. My objective is t ...

Error encountered while attempting to build Ionic 5 using the --prod flag: The property 'translate' does not exist on the specified type

I encountered an error while building my Ionic 5 project with the --prod flag. The error message I received is as follows: Error: src/app/pages/edit-profile/edit-profile.page.html(8,142): Property 'translate' does not exist on type 'EditProf ...

Is there an alternative to RequestOptionsArgs that I can use in this function?

I am currently working on updating an existing Angular application from version 4.3 to Angular 8. One of the challenges I'm facing is replacing old component classes like ConnectionBackend, RequestOptions, and RequestOptionsArgs with their updated equ ...

Self-referencing type alias creates a circular reference

What causes the discrepancy between these two examples? type Foo = { x: Foo } and this: type Bar<A> = { x: A } type Foo = Bar<Foo> // ^^^ Type alias 'Foo' circularly references itself Aren't they supposed to have the same o ...

Retrieve a designated text value from a Promise

I have developed a React/Next.js application that utilizes what3words to assign items to specific locations. The code I've created processes the what3words address, converts it into coordinates, and is intended to display the location on a Mapbox map. ...

Struggling to locate the module in React Native with TypeScript configuration

Currently, I am in the middle of transitioning our react-native project from JavaScript to TypeScript. As I attempt to import old modules, I keep encountering the following error: Cannot find module 'numeral' Oddly enough, the 'numeral&apo ...

Struggling to effectively organize data routing within Angular? Let's tackle the challenges of

As a newcomer to Angular, I initially had success with CRUD operations without using routing. However, after implementing routing, I encountered an issue where the added values were not displaying in the content table on another page. It seems like there ...

Updating input values in Angular reactive forms

I have a repeated table row that includes a form. I need to dynamically update the total field based on the price and quantity in my reactive forms setup. Here is the code snippet: <tbody formArrayName="products"> <tr *ngFor="let phone of pro ...

Angular is detecting an incorrect value in the mask

Recently, I came across the library found at and decided to create a directive utilizing it. My TypeScript code snippet: initForm() { this.form = this.fb.group({ item_number: [this.service.lpu.item_number, Validators.required], ...

Expandable rows within an Angular Material table (mat-table) feature a distinct gap, even when rows are collapsed

I recently integrated an Angular Material table into my website, following the examples provided on the official Angular page (link to the examples). I wanted the table rows to be expandable similar to the "Table with expandable rows" example on the Angula ...

Running several angular 2 applications and an API on a single server using nginx

I am attempting to configure nginx in order to achieve the following setup: mydomain.com/api should serve the php API mydomain.com/login should serve an angular 2 app mydomain.com/dashboard should serve another angular 2 app The nginx.conf p ...

Prevent all dates from being selected except for the last day of every month in the Angular Material Calendar component

Is it possible to restrict all dates except the final day of each month with Angular Material? I need users to only be able to select this particular date. There is a [matDatepickerFilter] property, but it seems to work only for a specific list of dates. ...

The execution of *ngSwitchCase in Angular seems to be faulty

I am new to Angular and currently working with the ngSwitch directive in my program. However, I have encountered an issue where *ngSwitchDefault is executing instead of *ngSwitchCase every time the program runs. Below is the code snippet that I am using: ...

What is the functionality of angular's @Attribute decorator?

Just starting out with Angular and diving into the world of decorators. While exploring the angular.io documentation, I found limited information on the @Attribute decorator. Can anyone provide me with some practical use cases for this? ...

In Angular 2, the validation fires once data has been submitted

In my HTML code, I have omitted the Form tag. The data is successfully clear and the route is injected as well. However, the validation occurs after submitting and creating a new entry. <div class="col-lg-6 col-md-8"> <inp ...

Incorporate a personalized button within the actions column of ng2-smart-table for Angular 2 development

Within the context of an ng2-smart-table component in Angular 2, I am attempting to include a new button within the actions column that, when clicked, will navigate to another page. Despite my efforts to implement this new button alongside the existing add ...

Angular Material sidebar small version with dropdown menus

I am currently using Angular 5 in conjunction with Material design. My application features a side navigation menu with an angular material navigation drawer mini variant, where the items are hidden, leaving only the icons when collapsed (see image). My g ...

Attempting to simulate the behavior of Angular2 Token during testing

Currently, I am working on obtaining a token that is required for API authentication to retrieve a list. My approach begins with importing the angular2-token library: import { Angular2TokenService } from 'angular2-token'; After this, I include ...

Access the JSON data containing sub array values and showcase them on an HTML page by utilizing ngFor

Greetings! I am currently working on a web application where I need to showcase student data that is being received in JSON format. Below is the TypeScript code snippet that outlines the structure of the student data: export interface studentData{ ...