简体   繁体   中英

Angular @input value when route change

I'm using Angular 8 and I have a two components: father and child.

The father component has to send an object or a string when the url parameters change.

In the father component I have written this code, that is able to understand if the url has changed and to set the urlParam for the child:

  this.activatedRoute.queryParamMap.subscribe((paramMap: ParamMap) => {
      this.urlParam = JSON.stringify(paramMap);
   
  });

father html:

<search [searchCriteriaForm]="searchCriteriaForm" [urlParam]="urlParam"></search>

In the child component, I have put this:

 @Input() set urlParam(urlParam: string) {
  console.log('The child has well received');
 }

When the url change I see that the data arrives to the father component but not to the child.

I have noted that when I load the page (the first time) the child receives very well the parameters but when I change the url (without to reload or refresh the browser page) only the father is able to see.

I'd suggest going reactive in this scenario since it's a bit difficult to pinpoint the issue.

import { BehaviorSubject } from 'rxjs';

// define this on field level
urlParam = new BehaviorSubject("");
//...

  this.activatedRoute.queryParamMap.subscribe((paramMap: ParamMap) => {
      this.urlParam.next(JSON.stringify(paramMap));
  });

html

<search [searchCriteriaForm]="searchCriteriaForm" [urlParam]="urlParam | async"></search>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM