我的 child 组件如何调用 Angular 2 中 parent 组件的方法?

How can my child component call a method on the parent component in Angular 2?

背景

假设我有一些 parent 组件,称它为 MatchList,它显示 Hero object 的列表,等等。每个 Hero object 都具有某些 table 中显示的属性。现在假设我还为每个 Hero 设置了一个按钮,该按钮 更新路线 、加载新视图并显示更多详细信息。

之前

http://heroic.com/match-list

之后

http://heroic.com/hero-84

问题

我的基本问题是:我想从我的 MatchList 模板中的按钮调用路由器的 navigate() 方法,但是当我尝试这样做时收到以下错误:

EXCEPTION: Error during evaluation of "click"BrowserDomAdapter.logError @ ... angular2.dev.js:21835 ORIGINAL EXCEPTION: TypeError: l_context.setPath is not a function... angular2.dev.js:21835 TypeError: l_context.setPath is not a function at ...

换句话说 看起来我无法在child 模板中引用parent 组件的路由器方法。

那么,Angular 2 中 child 组件访问 parent 组件(或 'context')的方法的正确和最佳方法是什么?

如果解决方案比

更干净,我会更喜欢
class parent {

     child: Child;

     constructor(...) {

        ...

        this.child.parent = this;

     }
}

示例代码

编辑 我将模板按钮更改为

(^click)="setPath(match.match_id)"

我不再收到错误消息,但没有任何反应 - 我什至没有收到确认点击的控制台日志。


到目前为止我所拥有的片段。

//Parent

    @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);

        }

    }

}

//Child

@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>

在这个问题的上下文中,即调用 parent router,事实证明答案是微不足道的。有关详细信息,请参阅 this plunker

主要的收获是给一个 child 组件一个 la

class ChildComponent {

    constructor(router: Router) {

        ...

    }

}

不会创建新路由器,它只是扩展了 parent 组件的现有路由器。因此,不需要引用 parent object。只需调用 child 路由器的方法,一切都会按预期进行。