Home > database >  Sending parameters from my home page to another page
Sending parameters from my home page to another page

Time:04-28

export class HomeComponent implements OnInit {  
selectedStartDatee: Date;
id:number;
...
constructor(
 this.selectedStartDatee = new Date(this.datepipe.transform(this.datenow, 'MM.dd.yyyy HH:mm:ss'));
    this.selectedStartDatee.setDate(this.selectedStartDatee.getDate() - 7);
this.id=2;
)

btnshowAnotherComponenet(){}
}

export class AnotherComponent implements OnInit {  
@Input date:Date
@Input id:number
}

When I click the button, another page will open in the new tab and I want to send the ID and date parameters to the page opened from my current page.

CodePudding user response:

You could use navigation parameters.

When you navigate to your other page in HomeComponent, use

// create parameterized link
const url = this.router.serializeUrl(this.router.createUrlTree(['/path/to/other/page'], { queryParams: { id: 'id', date: 'date' } }));
// open link in new tab
window.open(url, '_blank');

And then in AnotherComponent, subscribe to your route's queryParams and do what you want with them:

// read in parameters
this.route.queryParams.subscribe(params => {
  this.id = params['id']
  this.date = params['date']
});

In the first chunk, router is a Router instance and in the second chunk route is an ActivateRoute instance.

CodePudding user response:

There are 2 ways of doing it.

  1. You can use a service that store your value, and use the service in your next page to retrieve the value.
export class HomeComponent implements OnInit {  

   selectedStartDatee: Date;
   id:number;

   constructor(yourService: YourService) { 

   }

   btnshowAnotherComponenet(){
      this.yourService.selectedStartDatee = selectedStartDatee;
      this.yourService.id = id;
      this.router.navigate(['/anotherComponent']);
   }
}

export class AnotherComponent implements OnInit { 
 
   selectedStartDatee: Date;
   id:number;

   constructor(yourService: YourService) { 
      this.selectedStartDatee = this.yourService.selectedStartDatee;
      this.id = this.yourService.id;
   }
}
  1. You can use query params
btnshowAnotherComponenet() {
  const url = this.router.serializeUrl(this.router.createUrlTree(['/anotherComponent']], {
     queryParams: { 
       selectedStartDatee : this.selectedStartDatee,
       id: this.id
     } 
  }));
  window.open(url, '_blank');
}

And in AnotherComponent:

ngOnInit() {
    this.route.queryParams
      .subscribe(params => {
        this.id = params['id'];
        this.selectedStartDatee = params['selectedStartDatee']
      }
    );
  }
  • Related