我有以下组件,一个主要的和另一个。我想以编程的方式从main导航到另一个。
主
/// <reference path="../../node_modules/angular2/typings/browser.d.ts" />
/// <reference path="../../node_modules/angular2/core.d.ts" />
/// <reference path="../../node_modules/angular2/router.d.ts" />
import {Component, provide} from 'angular2/core';
import {RouteConfig, Router, ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from 'angular2/router';
@RouteConfig([
{ path: '/Main/...', name: 'Main', component: Main}
])
@Component({
directives: [ROUTER_DIRECTIVES],
providers: [ROUTER_PROVIDERS],
selector: 'Main',
template:
'<div>
<button type="button" (click)="navigate()">Navigate</button>
</div>'
})
export class Main {
constructor(private _router: Router) { }
navigate() {
this._router.navigateByUrl('Another');
}
}另一个
/// <reference path="../../node_modules/angular2/typings/browser.d.ts" />
/// <reference path="../../node_modules/angular2/core.d.ts" />
/// <reference path="../../node_modules/angular2/router.d.ts" />
import {Component, provide} from 'angular2/core';
import {RouteConfig, Router, ComponentInstruction, OnActivate, ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from 'angular2/router';
@RouteConfig([
{ path: '/Another/...', name: 'Another', component: Another}
])
@Component({
directives: [ROUTER_DIRECTIVES],
providers: [ROUTER_PROVIDERS],
selector: 'Another',
template:
'<div [style.display]="isActive()">
<h1>i'm another!</h1>
</div>'
})
export class Another implements OnActivate {
constructor(private _router: Router) { }
IsActive = false;
isActive() {
return (this.IsActive === true) ? 'block' : 'none';
}
routerOnActivate(next: ComponentInstruction, prev: ComponentInstruction) {
this.IsActive = true;
console.log("called! surprisingly.");
}
}routerOnActivate似乎从未被调用过,尽管浏览器中的URL显示了Main/Another。为什么不叫它?
发布于 2016-04-18 15:48:22
事实证明,如果计划使用Angular2路由器导航到组件,则不应该引导组件。您需要在项目规划阶段规划您的导航策略。这将是典型的模式,意味着您将有父/子关系,并根据标志或路由模式隐藏/显示,这意味着您不会在父模板中引导或添加组件标记,而是使用角的路由器。角度本身将负责所有的导航和显示/隐藏的组件自动。所需要的就是RouteConfig和引导您的主要组件。
还请注意,angular2教程并不适合特定的语言。如果您有一个带有path www.something.com/angular/router的ASP.NET MVC网站,那么RouteConfig中的/不是www.something.com/,而是整个URL。
关于RouteConfig路径,您只需要为每个组件定义子导航。
发布于 2016-04-17 01:59:23
您到Another的路由是非终端路由,因为在最后使用了...。
您需要在模板中包含<router-outlet></router-outlet>,以便路由器知道在哪里呈现。
如果要导航到路径/,则需要在@RouteConfig for Another中创建带有path Another的默认路由。
{ path: '/', name: 'AnotherDefault', component: AnotherDefault, useAsDefault: true }另一种选择是将...从路径的末尾移除,例如,如果您想导航到它,请使用path: '/Another'。
https://stackoverflow.com/questions/36667777
复制相似问题