简体   繁体   English

Angular2:使用不同的ID渲染相同的组件

[英]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. 按钮使用不同的参数路由到同一组件dashboard 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. 在仪表板上我只是根据从顶栏按钮传递的参数更新iframe的源URL。
Once dashboard component loads first time, constructor(), ngOnit or ngOnChange do not get called when the buttons get clicked from the top-bar. 一旦仪表板组件第一次加载,当从顶栏单击按钮时,不会调用constructor(),ngOnit或ngOnChange。 Here is the code: 这是代码:
app.component.html 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 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? 如何将顶部栏中的按钮ID传递到仪表板组件并刷新页面?

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
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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