route类包括2个比较关键的属性:path和component,通过访问path,可以找到唯一的component。
在forRoot里添加上包含主页和详情页2个component的route数组。
RouterModule.forRoot([
{
path: '',
component: AppComponent
},
{
path: '',
component: GundamDetailComponent
}
])
app.module.ts现在看起来是这样的:
import {
NgModule
} from '@angular/core';
import {
BrowserModule
} from '@angular/platform-browser';
import {
FormsModule
} from '@angular/forms';
import { RouterModule } from '@angular/router';
import {
AppComponent
} from './component/appcomponent/app.component';
import { GundamDetailComponent } from './component/detail/gundam-detail.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot([
{
path: '',
component: AppComponent
},
{
path: '',
component: GundamDetailComponent
}
])
],
declarations: [
AppComponent,
GundamDetailComponent
],
bootstrap: [AppComponent],
})
export class AppModule {}
2个path都还空着,因为还少一个关键的东西,就算写上也会报错:

Error: Cannot find primary outlet to load ‘AppComponent'
在angular里,router是要搭配标签router-outlet来使用的,换句话说router决定显示哪个组件,而由router-outlet决定显示在哪里。
在app.component.ts里的template加上标签
<router-outlet></router-outlet>

然后不出意外的显示了2个主页:

app.component.ts是一个组件也是一个页面,angular先从bootstrap里进入了app.component.ts渲染了界面(也就是router-outlet上面的部分)。碰到又去找router,发现对应的router也有组件,于是又加载了一遍。
所以为了正常显示,也要把主页也单独抽出来。所有组件通过app.component.ts里的来进行加载。而app.component.ts作为整个demo的最外层容器可以进行一些公共的操作(典型:后退动作)。
在src下新建host包,新建gundam-host.component.ts文件。
基本上可以把整个app挪过来,删除掉out标签,删掉selector(暂时用不到)。
import {
Component
} from '@angular/core';
import { Gundam } from '../../model/gundam';
import { GUNDAMS } from './../../service/data';
@Component({
template: `
<div *ngFor="let gundam of gundams" (click)="onSelected(gundam)">
<span>
{{gundam.name}}
</span>
</div>
`
})
export class GundamHostComponent {
gundam: Gundam = {
name: '海牛',
type: 'NewType'
};
gundams = GUNDAMS;
selectedGundam: Gundam; // 定义一个selectedGudam作为展示详情的变量
onSelected (gundam: Gundam): void {
this.selectedGundam = gundam; // 通过参数赋值
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
