样式绑定
样式绑定可以根据某些条件达成或否,使用语法为[class.classname]
如果hero === selectedHero
条件成立,则会添加css
类为hero
html
<li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
父子传值
在组件嵌套过程中,如果需要父组件向子组件传值
- 父组件使用子组件选择器
html
<son></son>
- 父组件为子组件进行属性赋值,传递变量
html
<son [son_var]='father_var'></son>
- 父组件定义
father-var
js
this.father_var = 'abc'
- 子组件定义
son_var
,并使用@Input()
装饰
js
@Input() son_var?: String;
路由
js
import { Router, ActivatedRoute, ParamMap, Params } from '@angular/router';
angular的路由中,主要包含如上三款api
要想在组件中使用路由服务,可以通过注入的方式
typescript
constructor(
private activateInfo:ActivatedRoute
private router:Router
)
Router
运行时执行的路由对象,可以通过navigate
于navigateByUrl
方法导航至指定路由
- 路由路径传参
typescript
this.router.navigate(
['/path', 1]
)
// path/1
- 路由传参
typescript
this.router.navigate(
['/path'],{
queryParams: {
id : 1,
other: 'abc'
}
}
)
// path?id=1
ActivateRouter
当前激活的路由对象,保存着当前路由信息,信息地址,路由参数等
- 查询路由参数:
params
js
/product?id=1&name=2
this.activateInfo.snapshot.params["id"]
typescript
this.route.params.subscribe(
params => {
this.name = params['id']
}
)
- 路由路径参数:
queryParams
js
{ path: /product/:id } => /product/1
this.activateInfo.snapshot.queryParams["id"]
typescript
this.route.queryParams.subscribe(
params => {
this.name = params['id']
}
)
- 路由包含数据获取:
data
typescript
{
path: '',
component: InterviewSetComponent,
data: {
title: '标题',
}
}
获取包含的title
数据可以
typescript
this.activateInfo.snapshot.data.title;
通配路由
当用户试图导航到那些不存在的应用部件时,在正常的应用中应该能得到很好的处理
要在应用中添加此功能,需要设置通配符路由
当所请求的 URL 与任何路由器路径都不匹配时,Angular 路由器就会选择这个路由
typescript
{ path: '**', component: }
重定向
要设置重定向,使用路由的redirectTo
属性完成
重定向路由需要一个 pathMatch
属性,来告诉路由器如何用 URL 去匹配路由的路径
js
{
path: '',
redirectTo: '/first-component',
pathMatch: 'full'
}, // redirect to `first-component`
pathMatch
的两个属性
full
: 匹配的路由完整等于path
所指明的属性
prefix
: 以指定的路径开头匹配即跳转