What is the most effective way to move specific data from one page to another in Angular/Typescript?

Welcome to my Main Page! https://i.stack.imgur.com/m9ASF.png This is where I want to start my journey. https://i.stack.imgur.com/E8pAW.png

My goal is to click the Last 1 Day button to redirect to another page with the date filter and ItemId values already selected.

Answer №1

In the world of Angular, passing data along routes using params is a common practice. This data can then be accessed in the destination component's ngOnInit method.

Alternatively, you could set up an observable that continuously broadcasts this data, allowing other components to subscribe and read it as needed.

The best approach ultimately depends on the specific requirements of your project.

Answer №2

Utilizing input variables for data input via HTML is a common practice, but I prefer utilizing a shared service as the most organized method. Services serve as singleton classes where global data can be stored and accessed through dependency injection.

To create a service specifically for a component, you can generate it using

ng g service file-path/service-name
. It is advisable to place the service in the same directory as your component.

Add your data and define default values or leave them undefined as needed.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class MyComponentService {
  selectedId?: number;
  startDate = '';
  endDate = '';
}

Inject the service into the component where values need to be set, such as the 'Main Page' in this context. Adjust the values based on your specific requirements.

export class MainPageComponent {
  constructor(private myCompService: MyComponentService) {}

  setSelectedId(id: number) {
    this.myCompService.selectedId = id;
  }

  setDates(startDate: string, endDate: string) {
    this.myCompService.startDate = startDate;
    this.myCompService.endDate = endDate;
  }
}

Inject the service into the component that will utilize the values.

export class MyComponent {
  constructor(public myCompService: MyComponentService) {
}
<input type="number" [value]="myCompService.selectedId" />
<input type="date" [value]="myCompService.startDate" />
<input type="date" [value]="myCompService.endDate" />

You can also create getters and setters to manipulate the data similarly to local variables.

export class MyComponent {
  constructor(private myCompService: MyComponentService) {}

  get selectedId() {
    return this.myCompService.selectedId;
  }

  set selectedId(id: number | undefined) {
    this.myCompService.selectedId = id;
  }

  get startDate() {
    return this.myCompService.startDate;
  }

  set startDate(date: string) {
    this.myCompService.startDate = date;
  }
  
  get endDate() {
    return this.myCompService.endDate;
  }

  set endDate(date: string) {
    this.myCompService.startDate = date;
  }
}
<input type="number" [value]="selectedId" />
<input type="date" [value]="startDate" />
<input type="date" [value]="endDate" />

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

How can I configure React Router V6 to include multiple :id parameters in a Route path, with some being optional?

Currently, I am utilizing react-router@6 and have a Route that was previously used in V5. The route is for vehicles and always requires one parameter (:id = vehicle id), but it also has an optional second parameter (:date = string in DD-MM-YYYY format): &l ...

Verify Angular route path using an interceptor

I have configured a route path like this: { path: 'user/:id/edit/:type', component: UserEditTypeComponent, }, I am trying to access this path from an interceptor using activated routes: constructor(private activatedRoute: ActivatedRout ...

How to Utilize Output() and EventEmitter() for Value Transmission in Angular Application

Last week I was successfully able to implement Output() and EventEmitter() in my Angular app. However, today I am facing a new challenge while trying to apply the same concept in a different scenario. I'm not sure what I might be overlooking. Firstly ...

Creating pagination functionality for a React Material table

Check out this Spring Boot endpoint that I use for retrieving items from the database: import React, { useEffect, useState } from "react"; // Additional imports export default function BusinessCustomersTable() { // Functionality and code impl ...

Angular 2.0.0 - Simulated File Loader

For my unit testing, I am facing the challenge of mocking the FileUploader class from ng2-file-upload. Can anyone guide me on how to accomplish this? import { FileUploader } from 'ng2-file-upload/ng2-file-upload'; @Component({ selector: &apos ...

Tips for receiving @ mentions in PrimeNg Editor using Quill and quill-mention with Angular

Currently, I have been given the task of adding a mentions feature to our text editors. The editor I am working with is the PrimeNg Editor, built on Quill. After some research, I came across the package quill-mention, which appears to be a potential soluti ...

Tips for obtaining a reference to the ngfor-list with a pipe implemented on it

When applying a filter to a list within an ngFor directive, such as *ngFor="data | pipe", it can be challenging to access the filtered data in the component class. One attempted solution is using *ngFor="data | pipe as filtereddata", but this approach seem ...

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

How can Multer library be effectively utilized to manage exceptions in NestJS controllers?

While working on creating a service to upload specific files from a Post multipart/form-data request, I came across an easy way to validate the fields count and name sent using the FileInterceptor decorator from @nestjs/platform-express. However, I'm ...

Is it feasible to integrate gMaps with Angular2? How can I go about accomplishing this task?

In developing a typeahead service for cities and similar functions, I require the use of a typeahead directive (ng2-bootstrap) with an array of strings provided by the service. Google Maps is my chosen solution for this task. Below is code extracted from ...

Setting up event listeners from a string array (using PIXI.js)

Hey there! I've encountered a bit of an interesting challenge that could easily be resolved by duplicating the code, but where's the fun in that? This project is more of an experiment for me, just to prove that I can do it. However, the idea has ...

The data type 'void | Observable<any>' cannot be assigned to the type 'ObservableInput<any>'. Specifically, the type 'void' cannot be assigned to 'ObservableInput<any>'

I encountered an error in my visual studio code: Argument of type '(query: string) => void | Observable' is not assignable to parameter of type '(value: string, index: number) => ObservableInput'. Type 'void | Observable& ...

Identify changes in an input property of an Angular component

I am currently working on an Angular component that includes an input called Person export class Person { public name = 'Initial Name'; } export class PersonComponent implements OnInit, OnChanges { @Input() public person: Person; ngOnCha ...

What is the best way to change a blob into a base64 format using Node.js with TypeScript?

When making an internal call to a MicroService in Node.js with TypeScript, I am receiving a blob image as the response. My goal is to convert this blob image into Base64 format so that I can use it to display it within an EJS image tag. I attempted to ach ...

Create a global variable by importing an external module in TypeScript

I am currently developing a TypeScript npm module called https://www.npmjs.com/package/html2commonmark. This module is versatile and can be utilized in nodejs (via require) as well as in the browser (by loading node_modules/html2commonmark/dist/client/bund ...

Typescript: defining an interface that inherits properties from a JSON type

When working with TypeScript, I've utilized a generic JSON type as suggested in this source: type JSONValue = | string | number | boolean | null | JSONValue[] | {[key: string]: JSONValue} My goal is to cast interface types matching JSON to and ...

Utilizing Angular 4 with Ahead-Of-Time compilation in combination with Electron, as well as

I am new to Angular/Typescript and currently developing a cross-platform Desktop application with Electron and Angular 4. My current challenge involves using a Service in different components, but I need this service to be loaded from a separate file based ...

The @Input decorator in Angular 2/4 is designed to only transfer fundamental values and not collections or complex data

I have encountered an issue while attempting to use @Input with a list of objects, where the @Input variable ends up being undefined. What is functioning properly can be seen in home.component.html: <p> <it-easy [mycount]="countItem" (result ...

What is the process for combining an object and a primitive type to create a union type?

Having a tricky time with Typescript and finding the correct typing for my variable. What seems to be the issue? The variable selected in my code can either be of type DistanceSplit or number. I have an array that looks like this: [-100, DistanceSplit, D ...

Uploading files using Remix.run: Transforming a File object into a string during the action

I'm currently developing a Remix application that allows users to upload files through a form. I have a handler function for handling the form submission, which takes all the form data, including file attachments, and sends it to my action. The probl ...