Darth Ionic Darth Ionic - 1 month ago 5
TypeScript Question

Change a HTML element in app.component dynamically

I have implemented angular2 routing and its working perfect. Then i got this crazy thought and couldn't find a solution for that.


Question: I have an app.component.html page with a navbar and a
jumbotron bootstrap element. The navbar has two links, one for home
page, and the other for settings page. I need to change the jumbotron
element to display "You are in Home page" from the HomeComponent variable when home link is clicked
and display "You are in Settings page" from the SettingsComponent variable, when settings link is clicked.
I know its possible but don't know how.


Visual Representation:

enter image description here

Here is my snippet:

app.component.html

<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Darth</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a [routerLink]="['']" [routerLinkActive]="['active']">Home</a></li>
<li><a [routerLink]="['settings']" [routerLinkActive]="['active']">Settings</a></li>
</ul>
</div>
</div>
</nav>

<div class="jumbotron">
<h1>Hello, world!</h1>
</div>

<div class="container-fluid">
<router-outlet></router-outlet>
</div>


Any advice would be helpful. Thank you.

I have uploaded the entire project in my github repo here

Answer

Edit: The proper way of doing it is to use services as outlined in "components communication through <router-outlet>"

One simple but not-so-clean way of doing it is to detect url changes by listening on router events.

You component code becomes

import { Component } from '@angular/core';
import {Router, NavigationEnd} from "@angular/router";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  currentMessage:string = "Hello, World";
  constructor(private activeRoute:Router) {

  }
  ngOnInit() {
    this.activeRoute.events.subscribe(this.onUrlChange.bind(this))
  }

  onUrlChange(ev) {
    if(ev instanceof NavigationEnd) {
      let url = ev.url;
      if(url.indexOf('settings') != -1)  {
          this.currentMessage = "Settings";
      } else {
        this.currentMessage = "Home";
      }

    }
  }
}

And you modify your jumptron to read the "currentMessage" variable

<div class="jumbotron">
  <h1>{{currentMessage}}</h1>
</div>
Comments