我的子组件如何在Angular 2中调用父组件上的方法?

时间:2015-11-12 04:17:50

标签: javascript angular

背景

假设我有一些父组件,称之为MatchList,它提供了Hero个对象的列表等等。每个Hero对象都具有某些表中显示的属性。现在假设每个Hero都有一个按钮,更新路径,加载新视图,并显示更多详细信息。

  

http://heroic.com/match-list

  

http://heroic.com/hero-84

问题

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

  

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>

1 个答案:

答案 0 :(得分:3)

在这个问题的背景下,即呼叫父母router,答案,结果是微不足道的。有关详细信息,请参阅this plunker

主要内容是将路由器提供给子组件

class ChildComponent {

    constructor(router: Router) {

        ...

    }

}

创建新路由器,它只是扩展了父组件的现有路由器。因此,避免了对父对象的引用的需要。只需调用childRouter的方法,一切都按预期工作。