Home > Software design >  How to transfer selected data from one page to another page in angular/ts?
How to transfer selected data from one page to another page in angular/ts?

Time:04-26

This is my Main Page enter image description here I want to redirect to this page enter image description here

I want to redirect to the other page by clicking the Last 1 Day button and have the date filter and ItemId values selected on the other page.

CodePudding user response:

You can pass data along routes with params and read those params at destination component's ngOnInit.

You could also do an observable that continually emits those data so other components could read them.

Really depends on your approach.

CodePudding user response:

You can use input variables to input data through html, but I find a shared service to be the cleanest way to handle it. Services are singleton classes where you can store global data that can be accessed through dependency injection.

You can make a service specifically for this component, generate it with ng g service file-path/service-name. Probably best to put it in the same directory as your component.

Add your data and set some default values, or just leave them undefined.

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

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

Inject the service into the component where you want to set values, the 'Main Page' in your case. Set the values according to your specific case.

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 use 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 make getters and setters to use the data as if they were 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" />
  • Related