我是 Angular 的新手,正在关注 Tour of Heroes tutorial来自官方网站。
我下载了第 5 部分教程,并看到了代码
@Component({
selector: 'my-heroes',
在其中一个组件中。阅读本教程的开头并查看文档,它说选择器与您的 HTML 中的元素匹配,但是当我检查下载示例中的所有 HTML 文件时,没有带有 <my-heroes></my-heroes>
的元素。标签。不过,它工作得很好,没有错误。
那么,selector: 'my-heroes'
的目的是什么? ?
我什至尝试将其名称更改为类似
selector: 'my-heroes223'
它继续工作,没有任何错误或警告。
注意:这不是任何帖子的重复问题。我的问题是“如果在文档中另有说明,为什么选择器没有任何效果”
最佳答案
是因为<router-outlet></router-outlet>
正在为您完成工作。
你可以检查app.component.ts
文件。里面template
他们定义了 router-outlet
.
这里是àpp.component.ts
中指定的两条路线
<a routerLink="/dashboard" routerLinkActive="active">Dashboard</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
它的作用是当你点击一个链接时 Dashboard or Heroes
它将检查适当的 component class
在 app-routing.module.ts
定义路由并相应显示内容的位置。
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: 'heroes', component: HeroesComponent }
];
这是 selector
的用例.
如果您想为您的应用添加页脚,请先使用 Angular cli
生成一个页脚组件像这样ng generate component footer
.然后你可以在 app.component.ts
中添加页脚像这样
<h1>{{title}}</h1>
<nav>
<a routerLink="/dashboard" routerLinkActive="active">Dashboard</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>
<app-footer></app-footer>
然后 footer component
将对 app 和 router-outlet
通用将负责加载哪个组件。
关于javascript - Angular 4 中的 "selector"有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45408443/