简体   繁体   中英

Angular2: Rendering the same component with different ids

I have a common top-bar with few buttons on it. Buttons route to the same component dashboard with different parameter. I want to read that parameter and make changes to the dashboard.
On Dashboard I am just updating the source url of the iframe based on the parameter passed from the top-bar buttons.
Once dashboard component loads first time, constructor(), ngOnit or ngOnChange do not get called when the buttons get clicked from the top-bar. Here is the code:
app.component.html

    <button md-button  [routerLink]="['/dashboard', 'first']"  id="first" class="top-link">First</button>
    <button md-button  [routerLink]="['/dashboard', 'second']" id="second" class="top-link">second</button>
    <button md-button  [routerLink]="['/dashboard', 'third']" id="third" class="top-link">third</button>

dashboard.component.ts

constructor(private route: ActivatedRoute, private sanitizer: DomSanitizer) {
    this.dashboardId = route.snapshot.params['id'];
    console.log("Constructor "+route.snapshot.params['id']);
    this.dashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.first_url);
  }

  ngOnInit() {
    console.log("OnInit "+this.route.snapshot.params['id']);
    //this.dashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.first_url);
  }

How can I pass the button id from top bar to dashboard component and refresh the page?

This is a normal behavior. You can subscribe to route change and update the component accordingly:

ngOnInit(): void {
    this.changeMeOnUpdate();
}

changeMeOnUpdate(){
    this.sub = this.activatedRoute
        .params
        .subscribe(params => {
            //do what you want with your params and update the component
        }
}

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