view raw
Darth Ionic Darth Ionic - 6 months ago 35
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:


<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Darth</a>
<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>

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

<div class="container-fluid">

Any advice would be helpful. Thank you.

I have uploaded the entire project in my github repo here


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";

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

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

  ngOnInit() {

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