Angular 2将组件A中的var传递给组件B

时间:2016-10-19 03:58:52

标签: angular

如何将slug放入items.component.ts中 网址就像这样http://domain.com/slug 因此,如果我点击导航项目,我想将slug传递给另一个组件。

navbar.component.html:

    <ul class="nav navbar-nav">
      <li *ngFor="let item of items"><a (click)="changeParam(item.slug)" [routerLink]="[item.slug]" [routerLinkActive]="['is-active']">{{item.name}}</a></li>
    </ul>

navbar.component.ts:

import { Component, OnInit} from '@angular/core';
import {ActivatedRoute} from "@angular/router";

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
changeParam($slug) {

  this.sluggie = $slug;
}
constructor() { }

ngOnInit() {
}

}

items.component.ts:

import { Component, OnInit ,  Output } from '@angular/core';
import {ItemService} from "./item.service";
import { Router, ActivatedRoute, Params } from '@angular/router';
@Component({
  selector: 'app-items',
  templateUrl: './items.component.html',
  styleUrls: ['./items.component.css'],
  providers: [ItemService]
})
export class ItemsComponent implements OnInit {

  id: string;
  private sub: any;

  constructor(private route: ActivatedRoute) {

  }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      this.id = params['slug'];
    });
  }


}

APP-component.html:

<div class="container">
    <app-navbar></app-navbar>
    <h1>
    {{title}}
    </h1>
    <router-outlet></router-outlet>
    <app-items></app-items>
</div>

2 个答案:

答案 0 :(得分:0)

当您点击导航栏上的任何链接(items.component.ts)时,也许您想要查看项目详情(navbar.component.ts)。

请查看Routing in angular2 revisitedAngular 2 Router。我认为他们对你有好处!

答案 1 :(得分:0)

要将其从NavbarComponent传递到ItemsComponent s id,您可以使用输出和模板变量

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
  @EventEmitter() slugChange:EventEmitter<any> = new EventEmitter<any>();
  changeParam($slug) {
    this.sluggie = $slug;
    this.slugChange.emit($slug);
  }
}
<div class="container">
    <app-navbar (slugChange)="items.id = $event"></app-navbar>
    <h1>
    {{title}}
    </h1>
    <router-outlet></router-outlet>
    <app-items #items></app-items>
</div>

这仅适用,因为<app-navbar><app-items>位于同一模板中。如果不是这种情况,请使用共享服务。