Change a HTML element in app.component dynamically

爷,独闯天下 提交于 2020-02-08 07:08:26

问题


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:

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


回答1:


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>


来源:https://stackoverflow.com/questions/40331382/change-a-html-element-in-app-component-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!