发表于: 2020-06-22 22:37:18
1 2153
今天完成的事情:今天尝试处理了一下组件之间的传值
明天计划的事情:继续后续的任务
遇到的问题:实际还是没太搞好明天再继续研究一下
收获:1.父级向子级传值,不管是属性,方法,还是整个父级对象this,都可以通过类似变量的形式传入,具体如下
<app-detail #detail msg="123"></app-detail> //传入的值不是变量
<app-detail #detail [msg]="parentMsg"></app-detail> //传入的是变量
import { Component, OnInit, Input } from '@angular/core';
// 通过input装饰器获取父级传过来的值
@Input() msg: string; //获取值
ngOnInit() {
console.log(this.msg, '-----子组件传过来的msg-----');
}
//直接 this 可以引用
2.父级获取子组件的信息
第一种可以通过ViewChild的方式进行获取
<app-detail #detail [msg]="parentMsg"></app-detail> //组件
import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
//引入 ViewChild
@ViewChild('detail') myDom: any;
ngAfterViewInit(): void {
console.log(this.myDom.msg);
this.myDom.run();
}
//直接就能获取子组件的数据
第二种通过@Output 和 EventEmitter获取
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
//子组件引入装饰器
@Output() private outer = new EventEmitter();
//定义@Output的装饰器
emitData() {
this.outer.emit('传入給父级的值');
}
//子组件emit给父级的方法
<button (click)="emitData()">提交数据给父级</button> //按钮触发
<app-detail #detail [msg]="parentMsg" (outer)="getChildMsg($event)"></app-detail>
//父级通过outer事件接受,参数是$event, outer必须和子组件定义的变量名一致
getChildMsg(msg) {
console.log(msg, '---从子集拿过来的值---');
}
// 父级获取emit传过来的值
3.兄弟之间传值通过localStorage或者是服务进行获取
路由跳转以及传参
1 获取在路由后面的参数
<a [routerLink]="['/list/nav','MALFUNCTION','WAITING']"></a>
这种方式需要在路由配置像这样:
{
// 报修列表导航快捷栏
path: 'list/nav/:repairType/:repairStatus',
},
可以通过这种方式获取传递的参数:
this.activatedRoute.params['value']['repairType'];
通过这种方式传递参数域名是这样的:http://localhost:4200/#/system_manage/user/position/list/repairType/6
缺点: 不能通过
http://localhost:4200/#/system_manage/user/position/list/直接访问地址,必须的加上参数否则出错
2 通过域名跳转的方式获取参数(http://localhost:4200/#/system_manage/repair/list?repairType=REPAIR&repairStatus=WAITING)
这种方式不需要再路由后面配置,解放路由,只需跟平常一样写路由如:
{
path: "list",
。。。。。。。。。。。。。
},
只需要在ts代码中写地址跳转:
this.router.navigate(['/system_manage/repair/list'], { queryParams: { 'repairType': 'CLEAN','repairStatus':'WAITING' } });
上面这种也可以传递多个参数
在comoent中需要这么获取‘?’ 后面的参数
this.activatedRoute.queryParams.subscribe((params:Params)=>{
this.repairType = params['repairType'];
this.repairStatus = params['repairStatus'];
});
这两种的方式获取传递参数的区别在于
this.activatedRoute.queryParams和this.activatedRoute.params
但是有时候会不成功,明天再继续研究一下
评论