Using Angular 4 to transfer data from a dynamic modal to a component

Currently implementing material design, I have set up a dialogService for dynamically loading MdDialog. My goal is to create a search dialog with filters that, upon submission, directs the user to a search-results component route. However, I am struggling to understand how to pass the search data to the search-results component.

./dialog-service.ts

@Injectable()
export class DialogService {
  private dynamicModalComponent: DialogComponent;

  public init(dynModal: DialogComponent) {
    this.dynamicModalComponent = dynModal;
  }

  public show(component: Type<any>, configuration?: MdDialogConfig) {
    this.dynamicModalComponent.showModal(component, configuration);
  }

  public hide() {
    this.dynamicModalComponent.hideModal();
  }
}

./modules/search.component.html

<div class="search-component">
  <h2>Search</h2>
  <md-input-container class="full-width search">
      <input mdInput placeholder="search" color="primary" />
  </md-input-container>
  <div class="radio-groups">
      <md-radio-group class="radio-buttons" [(ngModel)]="searchFilterValue">
          <md-radio-button class="r-button" [value]="sf.value" *ngFor="let sf of searchFilter">
              {{sf.name}}
          </md-radio-button>
      </md-radio-group>
  </div>
  <md-dialog-actions class="actions">
      <button md-button (click)="hide()">Cancel</button>
      <button md-raised-button (click)="search()" color="primary">Search</button>
  </md-dialog-actions>
</div>

./modules/search.component.ts

import {Component, OnInit} from "@angular/core";
import {DialogService} from "../dialog/dialog.service";
import {Router} from "@angular/router";

@Component({
  selector: 'search',
  templateUrl: './search.component.html',
  styleUrls:['./search.component.scss']
})
export class SearchComponent implements OnInit {
  searchFilterValue;
  searchFilter = [
      {
          name: 'Groups',
          value: 'groups',
      },
      {
          name: 'People',
          value: 'users',
      },
      {
          name: 'Events',
          value: 'events',
      },
      {
          name: 'Posts',
          value: 'posts',
      }
  ];

  constructor(private _dialogService: DialogService,
              private router: Router){
      this.searchFilterValue = 'groups';
  }

  ngOnInit(){}

  hide() {
      this._dialogService.hide();
  }

  search() {
      this.hide();
      this.router.navigate(['/search']);
  }
}

Answer №1

There are a few different routes you could take:

1) One approach is to utilize optional or query routing parameters. When using router.navigate, you can include these parameters to pass data between components. This method is ideal for directly passing information from one component to another.

2) Alternatively, you could create a service to store search filter values. The search component would update the values in the service, and other components can then access those values through the service.

Do either of these options seem like they could be a good fit for your situation?

Answer №2

To incorporate a hide/close event, consider defining an output event and passing the result as an event argument. This allows other components to subscribe to the event in order to handle the result effectively.

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

Having trouble with the Cordova button not functioning on Android 9? A beginner seeks assistance

I attempted to create a button with the id of "clickme" that links to index.html and js/buttonexample.js. Although I could see the button on both the browser and android emulator, it wasn't functioning as expected when clicked. js/buttonexample.js d ...

Using JavaScript AJAX to send a PHP POST request

I am encountering an issue where my data is not being inserted into the database. When I check the console log and network, I receive a blank response. The problem might stem from the fact that my JavaScript source code contains a mix of other stack overfl ...

Changing the Value of an Input Element Dynamically in React: A Step-by-Step Guide

In a scenario where I have a component that takes an element, such as <input />, and I need to update its value programmatically after 15 seconds. Initially, I had the following approach in mind: const MyComponent = (myInput: JSX.Element) => { ...

Invoking Ajax within a for loop

for (var i = 0; i < 5; i++) { using (x = new XMLHttpRequest()) sendRequest("GET","d.php?id=" + i), checkResponse(null), updateStatus = function() { if (x.state == 4 && x.responseCode == 200) notifyUser(i); } } My goal now is to e ...

Establishing a standard value for a class that can be injected

Here is my desired approach: @Injectable() export class MyInjectableClass { constructor(timeout: number = 0) { } } The goal is to have the timeout set to 0 when it's injected, but allow the calling code to specify a different value when constr ...

How can I arrange a table in Angular by the value of a specific cell?

Here's the current layout of my table: Status Draft Pending Complete I'm looking for a way to sort these rows based on their values. The code snippet I've been using only allows sorting by clicking on the status header: onCh ...

Creating custom CSS for Styled Components in ReactJS

I'm struggling with CSS in React using styled components. Below is the code snippet I am working with: import React from 'react'; import { Navbar, Container, Row, Col } from 'reactstrap'; import styled from 'styled-components& ...

The functionality of lazy loading and routing in Angular 10 appears to be malfunctioning

I recently attempted to implement routing and lazy loading in Angular 10.1.6, but for some unknown reason, I've encountered issues where the routing and lazy loading of a module simply isn't functioning as expected. Despite referring to the offic ...

Using AngularJS Services to Share Objects Between Views and Controllers

I'm finding it difficult to grasp the concept of AngularJS services as I am fairly new to AngularJS. My goal is to pass a nested object between two controllers/views. In my home page partial, I have a section that displays the project and task. hom ...

best practices for filtering custom data returned from valuePreparefunction in ng2 smart table

Having an issue with the filter in ng2 smart table because I am returning custom data from the valueprepareFunction. This is my setup... columns: { id: { title: 'Id', type: 'string' }, surname: { title: 'surname', ty ...

How can I ensure that reactive form fields are properly validated in Angular2?

I am currently facing issues with validating Reactive form field in Angular 2. I have implemented a custom validator for this purpose, but it seems like my approach is not yielding accurate results as some of the test cases are failing. If anyone has insig ...

What steps do I need to take for the function to accurately determine the return type?

class Foo { name: string; constructor({name}: {name: string}) { this.name = name; } } class Bar<T extends Foo> { foo: T; constructor({foo}: {foo: T}) { this.foo = foo; } } class CustomFoo extends Foo { xxx: string; constr ...

Is there a way to display a loader when an item is selected from a dropdown menu? For example, while data is being fetched from the backend, can we

This is the HTML form division I have created: <div class="col-lg-2 "> <select name="limitCount" id="limitCount" ng-model="limitCount" class="form-control col-md-2 panel-refresh" ...

Angular JS Troubleshooting: Application Not Functioning Properly

I've been learning AngularJS on codeSchool and I ran into an issue with my simple hello world app. It was working fine at first but then stopped completely. I can't seem to find the bug, so any help would be appreciated. Here is the HTML code: & ...

Utilizing node-json2html, generate individual HTML tables for each record

I need assistance in consolidating my JSON data into a single HTML table, instead of generating separate tables for each record through my current transformation process. var data=[{"name":"aa","mid":"12345","user":"a123","password":"a@123"},{"name":"bb" ...

Using jQuery Validation for implementing a step-by-step validation process in a wizard form

Looking for a way to implement the jQuery Validation Plugin in conjunction with jQuery UI Tabs? How can I use the jQuery Validation Plugin to validate each step triggered by the next button when using tabs? Most examples of the jQuery Validation Plugin foc ...

Error: The function $.simpleTicker is not defined

Every time I try to call a jQuery function, an error shows up: Uncaught TypeError: $.simpleTicker is not a function I attempted changing $ to jQuery but it didn't resolve the issue. This represents my jQuery code: (function ($) { 'use ...

Send a parameter to an Angular directive when clicked

I am working on a directive that will allow me to retrieve parameters upon clicking. I need to access the child data within the click event to determine if it has children or not. ..... html div ng-app="treeApp"> <ul> <treeparent>< ...

What is the best way to create a generic array and combine properties?

I have a scenario where I have two objects defined as one and two, each containing props. These objects are then stored in an array called packages. const one = { props: { num: 2 } } const two ={ props: { nam ...

Updating Angular components by consolidating multiple inputs and outputs into a unified configuration object

When I develop components, they often begin with numerous @Input and @Output properties. However, as I continue to add more properties, I find it beneficial to transition to utilizing a single config object as the input. For instance, consider a component ...