Angular 样式绑定以及父子传值还有路由

样式绑定

样式绑定可以根据某些条件达成或否,使用语法为[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>

父子传值

在组件嵌套过程中,如果需要父组件向子组件传值

  1. 父组件使用子组件选择器
html 复制代码
<son></son>
  1. 父组件为子组件进行属性赋值,传递变量
html 复制代码
<son [son_var]='father_var'></son>
  1. 父组件定义father-var
js 复制代码
this.father_var = 'abc'
  1. 子组件定义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: 以指定的路径开头匹配即跳转

相关推荐
Warson_L4 天前
上传头像 (angular 16)
前端·angular.js
Warson_L5 天前
# Angular 速查手册 (Angular 16 手册)
angular.js
鶴哥只手遮天18 天前
Angular 22 源码级深度解析-第 13 章 依赖注入(一):Injector 抽象、`R3Injector` 与 bloom filter
前端·开源·angular.js
鶴哥只手遮天19 天前
Angular 22 源码级深度解析-第 06 章 模板指令全解:`ɵɵelementStart`、`ɵɵproperty`、`ɵɵadvance` 与绑定指令
前端·开源·angular.js
鶴哥只手遮天20 天前
Angular 22 源码级深度解析-第 02 章 编译链路总览:从模板字符串到 `ɵɵ` 指令
前端·开源·angular.js
starrysky8101 个月前
你的 Ollama 可能正被别人用:CVE-2024-37032 完整攻击链与 3 条自查命令
angular.js
starrysky8102 个月前
明明在赋值前读取,为什么还报 UnboundLocalError?——从 CPython 符号表拆解函数级作用域
angular.js
starrysky8102 个月前
只填了个模型地址,5 秒就被接管——Open WebUI 攻击链拆解与「被拒 CVE」的坑
angular.js
大雄很用心2 个月前
package.json 中的 dependencies 是否都会被下载?|Angular 回归笔记 02
angular.js
starrysky8102 个月前
同一个 submit(),两条报错——ThreadPoolExecutor 在解释器退出时的竞态(附 4 组可复现实验)
angular.js