angular传参的三种方式

angular传参的三种方式

1.routerLink

单一参数:在<a routerLink=["/exampledetail",id]>中加routerLink进行跳转,其中/exampledetail是我设置的路由path,id是需要传递的参数。
多个参数:如果要传多个参数,则可以写成routerLink=["/exampledetail",{queryParams:object}] ,queryParams携带多个参数,这个参数的格式可以是自行组织的object,也可以分开多个参数写成routerLink=["/exampledetail",{queryParams:‘id’:‘1’,‘name’:‘yxman’}];。

2.router.navigate

单一参数:this.router.navigate([’/exampledetail’,id]); ,多用在调用方法里
多个参数:this.router.navigate([’/exampledetail’],{queryParams:{‘name’:‘yxman’}});

3.router.navigateByUrl

单一参数:this.router.navigateByUrl(’/exampledetail/id’);
多个参数:this.router.navigateByUrl(’/exampledetail’,{queryParams:{‘name’:‘yxman’}});
传参方传参之后,接收方2种接收方式如下:

1.snapshot
import { ActivateRoute } from '@angular/router';
public data: any;
constructor( public route: ActivateRoute ) { };
ngOnInit(){
this.data = this.route.snapshot.params['id'];
};
2.queryParams
import { ActivateRoute } from '@angular/router';
public data: any;
constructor( public activeRoute:ActivateRoute ) { };
ngOnInit(){
this.activeRoute.queryParams.subscribe(params => {
this.data = params['name'];
});
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular中,可以使用参数传递来向组件传递数据。有几种不同的方式可以实现参数传递: 1. 通过路由传递参数:可以在路由配置中定义参数,并在URL中传递参数值。在组件中,可以使用ActivatedRoute服务来访问传递的参数。例如: 在路由配置中: ``` { path: 'example/:id', component: ExampleComponent } ``` 在组件中: ```typescript import { ActivatedRoute } from '@angular/router'; constructor(private route: ActivatedRoute) { } ngOnInit() { this.route.params.subscribe(params => { const id = params['id']; // 使用传递的参数 }); } ``` 2. 通过属性绑定传递参数:可以在组件模板中使用属性绑定来传递参数。在父组件中,使用属性绑定将数据传递给子组件。在子组件中,通过@Input装饰器接收传递的参数。例如: 在父组件模板中: ```html <app-child [param]="value"></app-child> ``` 在子组件中: ```typescript import { Input } from '@angular/core'; @Input() param: any; // 使用传递的参数 ``` 3. 通过服务传递参数:可以创建一个共享的服务,在多个组件之间共享数据。在提供者中定义一个属性来保存要传递的参数,在需要使用参数的组件中注入该服务并访问参数。例如: 创建一个参数服务: ```typescript import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ParamService { param: any; } ``` 在组件中使用参数服务: ```typescript import { ParamService } from './param.service'; constructor(private paramService: ParamService) { } ngOnInit() { const param = this.paramService.param; // 使用传递的参数 } ``` 以上是一些常见的Angular中传递参数方式,你可以根据你的需求选择适合的方式来传递参数。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值