Angular 2 wrap-up: How to seamlessly transfer filter data from Filter Component to App Component

A filtering app has been created successfully, but there is a desire to separate the filtering functionality into its own component (filtering.component.ts) and pass the selected values back to the listing component (app.ts) using @Input and @Output functions properly. The current setup where the filtering and listing are in the same component can be found here: http://plnkr.co/0eEIJg5uzL6KsI70wWsC

@Component({
  selector: 'my-app',
  template: `
  <select name="selectmake" [(ngModel)]="makeListFilter" (ngModelChange)="selectMake()">
    <option *ngFor="let muscleCar of muscleCars" [ngValue]="muscleCar">{{muscleCar.name}}</option>
  </select>

  <select name="selectmodel" [(ngModel)]="modelListFilter">
    <option *ngFor="let m of makeListFilter?.models" [ngValue]="m.model">{{m['model']}}</option>
  </select>

  <button class="btn btn-default" type="submit" (click)="searchCars()">FILTER</button>

  <ul>
    <li *ngFor="let _car of _cars | makeFilter:makeSearch | modelFilter:modelSearch">
        <h2>{{_car.id}} {{_car.carMake}} {{_car.carModel}}</h2>
    </li>
  </ul>`,
  providers: [ AppService ]
})

export class App implements OnInit {
  makeListFilter: Object[];
  modelListFilter: string = '';

  _cars: ICar[];

   constructor(private _appService: AppService) { }

  ngOnInit(): void {
    this._appService.getCars()
        .subscribe(_cars => this._cars = _cars);
  }

  selectMake() {
    if(this.modelListFilter) {
      this.modelListFilter = '';
    }
  }
  searchCars() {
    this.makeSearch = this.makeListFilter['name'];
    this.modelSearch = this.modelListFilter;
  }

The components have already been separated in this example, however, there seems to be an issue with passing data to the listing component. You can view the separation here: http://plnkr.co/1ZEf1efXOBysGndOnKM5

Any help or suggestions on how to resolve this issue would be greatly appreciated.

Answer №1

Whenever the button is clicked, an output needs to be displayed,

Take a look at this Plunker

filter component

export class FilterComponent {
  @Output() filtercars: EventEmitter<{make: string, model: string}> = new EventEmitter<{make: string, model: string}>();

  makeListFilter: Object[];
  modelListFilter: string = '';

  constructor(private _appService: AppService) {}

  selectMake() {
    if(this.modelListFilter) {
      this.modelListFilter = '';
    }
  }

  searchCars() {
    this.filtercars.emit({make: this.makeListFilter['name'],model: this.modelListFilter});
  }

  muscleCars = [
    {
      id: 1, name: "Chevrolet", models: [
        { model: "Camaro" },
        { model: "Corvette" }
      ]
    },
    {
      id: 2, name: "Dodge", models: [
        { model: "Challenger" },
        { model: "Charger" },
        { model: "Viper" }
      ]
    },
    {
      id: 3, name: "Ford", models: [
        { model: "GT" },
        { model: "Mustang" }
      ]
    }
  ];
}

app component

@Component({
  selector: 'my-app',
  template: `
  <filter-app (filtercars)='filtercars($event)'></filter-app>
  <ul>
    <li *ngFor="let _car of _cars | makeFilter:makeSearch | modelFilter:modelSearch">
        <h2>{{_car.id}} {{_car.carMake}} {{_car.carModel}}</h2>
    </li>
  </ul>`,
  providers: [ AppService ]
})
export class App implements OnInit {

  @Input() makeSearch: Object[];
  @Input() modelSearch: string = '';

  _cars: ICar[];

  constructor(private _appService: AppService) { }

  ngOnInit(): void {
    this._appService.getCars()
        .subscribe(_cars => this._cars = _cars);
  }

  filtercars(filter){
     this.makeSearch = filter.make;
    this.modelSearch = filter.model;
  }
}

I trust this information will be useful!

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

What is the process for importing types from the `material-ui` library?

I am currently developing a react application using material-ui with typescript. I'm on the lookout for all the type definitions for the material component. Despite attempting to install @types/material-ui, I haven't had much success. Take a look ...

Is MongoDB still displaying results when the filter is set to false?

I am currently trying to retrieve data using specific filters. The condition is that if the timestamp falls between 08:00:00 and 16:00:00 for a particular date, it should return results. The filter for $gte than 16:00:00 is working correctly, but the $lte ...

Access information from your own API endpoint and incorporate it with an interface

Trying to retrieve the json-data from an api-server but encountering difficulties adding it to the variable. The error received is: Type is missing the following properties from Type "Observable" missing the properties from type "GAMELIST[]": "length, p ...

Guide to implementing ES2022 modules within an extension

After making changes in my extension code to test various module types, I decided to modify my tsconfig.json file as follows: { "compilerOptions": { "declaration": true, "module": "ES2022", ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

What is the most effective way to code and define a MatSelect's MatSelectTrigger using programming techniques?

How can I programmatically set the MatSelectTrigger template for a MatSelect instance using the provided reference? The documentation mentions a settable customTrigger property, but information on the MatSelectTrigger class or how to create one dynamically ...

Specialized spinning tool not in sight

Having an angular 11 application with a spinner that should be visible during data loading from the backend. However, when the fa-icon is pressed by the user, it becomes invisible while waiting for the server response. The issue arises when the spinner its ...

Typescript throws an error when Redux useSelector fails to properly infer the state

Seeking guidance on how to access my state using the useSelector hook import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { reducers } from './reducers'; export c ...

Creating a form with multiple components in Angular 6: A step-by-step guide

I'm currently working on building a Reactive Form that spans across multiple components. Here's an example of what I have: <form [formGroup]="myForm" (ngSubmit)="onSubmitted()"> <app-names></app-names> <app-address> ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Encountering an issue in Angular 8 flex-layout 8: Unable to export member ɵNgClassImpl

I encountered an issue while trying to install flex-layout 8.0.0-beta.26 in my Angular 8 project. The error I received during the build process is as follows: ERROR in node_modules/@angular/flex-layout/extended/typings/class/class.d.ts(9,19): error TS2305 ...

Reset the angular child component trigger by its parent component, which is a modal popup

I'm facing an issue with my Angular application where I have a child component within a parent modal window implemented using ngx-smart-modal. When I close the modal using the method: this.ngxSmartModalService.getModal('ModalNameComponent') ...

The TypeScript error ts2322 occurs when using a generic constraint that involves keyof T and a

Trying to create a generic class that holds a pair of special pointers to keys of a generic type. Check out an example in this playground demo. const _idKey = Symbol('_idKey') const _sortKey = Symbol('_sortKey') export interface BaseSt ...

Tips for monitoring and automatically reloading ts-node when there are changes in TypeScript files

I'm experimenting with setting up a development server for my TypeScript and Angular application without having to transpile the .ts files every time. After some research, I discovered that I am able to run .ts files using ts-node, but I also want th ...

Issue with iPad Pro displaying Bootstrap 4 Navbar toggle icon

Having trouble with my Bootstrap 4.1.1 navbar on iPadPro. It's not displaying the correct data from the div and it's not collapsing properly. However, it works fine on small devices. Any suggestions on how to fix this issue? Here's the code ...

Retrieve contextual information within standard providers

I'm currently using nestjs to create a straightforward HTTP rest API, utilizing typeorm. I have set up 2 Postgres databases and would like the ability to access both, although not necessarily simultaneously. Essentially, I am looking to designate whi ...

The parameter 'data' is assumed to have an 'any' type in React hooks, according to ts(7006)

It's perplexing to me how the 7006 error underlines "data," while in the test environment on the main page of React Hooks (https://react-hook-form.com/get-started#Quickstart), everything works perfectly. I'm wondering if I need to include anothe ...

Supertest and Jest do not allow for sending JSON payloads between requests

Below is the test function I have written: describe("Test to Create a Problem", () => { describe("Create a problem with valid input data", () => { it("Should successfully create a problem", async () => { const ProblemData = { ...

react-mock-store: Error - the middleware function is not defined

In my current setup, I am utilizing jest for testing with React and Typescript. import configureStore from "redux-mock-store"; import thunk from "redux-thunk"; const mockStore = configureStore([thunk]); it("should handle fetchCha ...

Angular and ag-Grid enable the addition of a convenient date picker to a date cell, simplifying the

Currently, I am working on an ag-grid in angular which has a cell containing a date. I want to enhance it by incorporating a date picker feature, however, the process seems quite intricate. My preferred choice would be to utilize mydatepicker, as it is alr ...