![](/img/trans.png)
[英]How to pass data received from dataService in parent to child in Angular2
[英]How to pass data from Child to Parent: Angular2
我在這里關注文檔: https : //angular.io/docs/ts/latest/cookbook/component-communication.html#!# child-to-parent
但是到目前為止,還不能將字符串變量從子級獲取到父級。
import { Component,
ChangeDetectionStrategy,
EventEmitter,
Output,
OnInit,
ViewEncapsulation } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.Emulated,
selector: 'category',
styleUrls: [ './category.component.css' ],
templateUrl: './category.component.html'
})
export class CategoryComponent implements OnInit {
title: string = '';
@Output() onCategoryTitled = new EventEmitter<string>();
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.title = this.route.snapshot.params['title'];
console.log('this.title', this.title)
this.onCategoryTitled.emit(this.title);
}
}
import { Component,
Directive,
ElementRef,
Renderer,
ChangeDetectionStrategy,
OnInit,
ViewEncapsulation } from '@angular/core';
@Component({
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.Emulated,
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
catTitle:string;
onCategoryTitled(cat_title: string) {
console.log('EVENT recieved cat_title:', cat_title)
this.catTitle = cat_title;
}
ngOnInit() {
console.log('AppComponent init')
}
}
<div class="container">
<div class="row"><div class="col-md-12 h20"></div></div>
<div class="row">
<div class="col-md-8 col-sm-8">
<ol class="breadcrumb">
<li><a href="/wiki">Home</a></li>
<li>{{ catTitle }}</li>
<!-- <li><a href="/wiki/category">Categories</a></li> -->
</ol>
</div>
<div class="col-md-2 col-sm-2">
<div class="input-group">
<input type="text" class="search-input form-control" placeholder="Search for...">
</div>
</div>
</div>
<router-outlet></router-outlet>
<footer class="container col-sm-12">
<p>©2017 <strong>WikiTags</strong>
</footer>
</div>
當子級直接嵌套在父級中時,將使用您從The Cookbook中嘗試的通信方法。 在這種情況下,您可以在Parent上將事件處理程序綁定到發出的事件,如其示例所示:
(onVoted)="onVoted($event)"
您的情況有所不同,因為您具有router-outlet
,該router-outlet
將組件動態地加載到父級中,並且引入了更多的復雜性。 您仍然需要綁定(或訂閱)該事件,但是(如您可能遇到的那樣)您不能像該簡單的菜譜示例所示將綁定直接添加到router-outlet
。 但是,您可以引入“中介”服務,該服務可以跨router-outlet
邊界為您傳達事件。
例如,您可以編寫某種“通訊”服務,如下所示:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MyCommunicationService {
constructor() { }
private emitChangeSource = new Subject<any>();
changeEmitted$ = this.emitChangeSource.asObservable();
// Service message
emitChange(myMessage: any) {
this.emitChangeSource.next(myMessage);
}
}
從您的子組件發出事件:
...
export class CategoryComponent implements OnInit {
constructor(private _myCommunicationService: MyCommunicationService) {}
doSomething(): void {
...
// Emit your event with message
this._myCommunicationService.emitChange('some change');
}
...
然后在包含router-outlet
的父組件(在您的情況下為app.component)中偵聽(訂閱)該事件:
export class AppComponent implements OnInit {
constructor(private _myCommunicationService: MyCommunicationService) {
// Subscribe to the service event
_myCommunicationService.changeEmitted$.subscribe(myMessage => {
// TODO: Do what you need to to with the message/value
...
});
}
}
讓我知道是否需要澄清。 (我也可能完全錯過了船,並假設子組件正在router-outlet
加載,而實際上您正在做的事情完全不同。)
注意:這是未經測試的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.