[英]How can i call the same child method when i have the list of same child component in parent component in angular
[英]How can my child component call a method on the parent component in Angular 2?
假設我有一些父組件,稱之為MatchList
,它提供了一個Hero
對象列表等等。 每個Hero
對象都具有某些表中顯示的屬性。 現在假設每個Hero
都有一個按鈕來更新路徑 ,加載新視圖並顯示更多細節。
之前
后
我的問題必不可少的是:我想從我的MatchList
模板中的按鈕調用路由器的navigate()
方法,但是當我嘗試這樣做時收到以下錯誤:
EXCEPTION:評估“click”時出錯BrowserDomAdapter.logError @ ... angular2.dev.js:21835 ORIGINAL EXCEPTION:TypeError:l_context.setPath不是函數... angular2.dev.js:21835 TypeError:l_context.setPath不是...的功能
換句話說 ,看起來我無法在子模板中引用父組件的路由器方法。
那么,對於子組件訪問父組件(或“上下文”)的方法,Angular 2中的正確和最佳方法是什么?
如果解決方案更清潔,我更願意
class parent {
child: Child;
constructor(...) {
...
this.child.parent = this;
}
}
編輯我將模板按鈕更改為
(^click)="setPath(match.match_id)"
我不再收到錯誤消息,但沒有任何反應 - 我甚至沒有得到確認點擊的控制台日志。
到目前為止我所擁有的片段。
//父
@Component({
selector: 'dota-app',
directives: [Home, MatchesView, ROUTER_DIRECTIVES],
templateUrl: 'AppView.html'
})
@RouteConfig([
{ path: '/', component: Home, as: 'Home' },
{ path: '/matches', component: MatchesView, as: 'Matches' },
{ path: '/match-details', component: MatchDetailsView, as: 'MatchDetails'}
])
export class RootDotaComponent {
router: Router;
constructor(router: Router) {
this.router = router;
}
public setPath(linkParams: any[]|string): void {
if (typeof linkParams === "string")
linkParams = [linkParams];
this.router.navigate(<any[]>linkParams);
}
}
}
//兒童
@Component({
selector: 'matches-view',
providers: [DotaRestDao],
})
@View({
templateUrl: './components/MatchesView/MatchesView.html',
directives: [CORE_DIRECTIVES]
})
export class MatchesView {
public result;
private dataService: DotaRestDao;
constructor(dataService: DotaRestDao) {
this.result = { matches: [] };
this.dataService = dataService;
this.dataService.getData({
baseUrl: DotaRestDao.MATCH_HISTORY_BASE
}).subscribe(
res => this.result = res.result,
err => console.log("something wrongable", err),
() => console.log('completed')
);
}
}
//模板
<table class="table">
...
<button (click)="setPath(match.match_id)">Match Detail Route</button>
</table>
在這個問題的上下文中,即調用父router
,事實證明,答案是微不足道的。 有關詳細信息,請參閱此plunker 。
主要內容是將路由器提供給子組件1a
class ChildComponent {
constructor(router: Router) {
...
}
}
不創建一個新的路由器,它只是擴展了父組件的現有的路由器。 因此,避免了對父對象的引用的需要。 只需調用childRouter的方法,一切都按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.