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

时间:2017-03-14 16:12:43

标签: javascript angular typescript

我有一个共同的顶栏,上面有几个按钮。按钮使用不同的参数路由到相同的组件dashboard。我想读取该参数并对仪表板进行更改。
在仪表板上我只是根据从顶栏按钮传递的参数更新iframe的源URL。
一旦仪表板组件第一次加载,当从顶栏单击按钮时,不会调用constructor(),ngOnit或ngOnChange。 这是代码:
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);
  }

如何将按钮ID从顶部栏传递到仪表板组件并刷新页面?

1 个答案:

答案 0 :(得分:0)

这是正常行为。 您可以订阅路由更改并相应地更新组件:

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

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