2016-10-19 5 views
1

Как получить пулю в items.component.ts Адрес такой как http://domain.com/slug Так что если я нажму на элемент nav, я хочу передать слизню в другой компонент.Угловой 2 проход var в компоненте A к компоненту B

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> 
+0

Как навигация и навигация связаны. Не могли бы вы добавить еще код. Какие селекторы имеют компоненты. См. Также https://angular.io/docs/ts/latest/cookbook/component-communication.html –

+0

Не зная селекторов рассматриваемых компонентов, я не знаю, где они применяются. –

+0

@Bas: Вы вызываете компонент элементов внутри компонента navbar? –

ответ

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> находятся в том же шаблоне. Если это не так, используйте общую услугу.

+0

Спасибо, но я получаю эту ошибку: Uncaught TypeError: Не удается установить свойство '_isScalar' undefined – Bas

+0

Что такое '_isScalar'? Я предполагаю, что это где-то в вашем коде. –

+0

Является ли ArrayLikeObservable. Это не сработает :(Я просто хочу, чтобы slug нажал на элемент nav, переходящий на items.component – Bas

0

Может быть, вы хотели бы, чтобы просмотреть подробную информацию о позициях (items.component.ts) при нажатии на любую ссылку на навигационной панели (navbar.component.ts).

Пожалуйста, взгляните на Routing in angular2 revisited или Angular 2 Router. Я думаю, они хороши для вас!

+0

Я погружаюсь в него, thnx – Bas

Смежные вопросы