Angular4+组件间传值

本文详细介绍了Angular中组件间通信的多种方式,包括父组件到子组件、子组件到父组件、兄弟组件间的通信,利用Service进行数据共享,以及通过路由、SessionStorage等途径传值的优缺点。

Angular4+组件间传值

1. 组件间通信

父组件传值给子组件

父组件:

<app-index [title]="title" [run]="run"></app-index>

子组件:

import { Input } from '@angular/core';
@Input() title;
@Input() run;
//这样就可以直接使用{{title}},和this.run在子组件使用父组件的值和方法。

子组件传值给父组件

子组件中:

import { EventEmitter, Input, Output } from '@angular/core';
@Output() selectionChange = new EventEmitter();
//事件中
 this.selectionChange.emit("我是子组件的数据");

父组件中

// selectionChange即是子组件发送的数据
<app-index (selectionChange)="getData($event)"></app-index>
// ts文件中:
getData(msg:string)
{
   console.log(msg);// 接收到的数据
}

父组件主动调用子组件(本地变量)

// 引用子组件
<app-index #index></app-index>
// 使用子组件中的方法
<button (click)="index.childRun()">调用index中的方法</button>

也可以在ts文件中调用:

// 引用子组件 html文件
<app-index #index></app-index>
<button (click)="parentClick(index)">调用index中的方法</button>
// ts 文件
parentClick(obj)
{
    obj.childRun();
}

ViewChild主动获取数据:

在页面中引入ViewChild

import { ViewChild } from '@angular/core';
@ViewChild("index") index;
// html中引用组件
<app-index #index></app-index>  //#index相当于是一个选择器,包含模板
<button (click)="parentClick()">调用index中的方法</button>
// ts文件中使用子组件的方法和数据
parentChild()
{
    this.index.childRun();
}
2.Service

建立一个中间service—MyService接收需要传递的数据

MyService.service.ts中

export class MyService {
   ids:any[];
}

one.component.ts(传递参数的组件)

  constructor(
    private myService: MyService,
  ) {
  }

ngOnInit() {
   this.myService.ids=[1,2,3]
}

two.component.ts(获取参数的组件)

myIds:any[];
constructor(
    private myService: MyService,
) {
}
ngOnInit) {
  this.myIds=this.myService.ids;(获取参数)
}

3.订阅

方法一

MyService中

  private Source = new Subject<any>();
  $status = this.Source.asObservable();
  StatusMission(ids: any) {
    this.Source.next(ids);
  }

one.component.ts(传递参数的组件)

ids=[1,2,3];
constructor(
  private myService: MyService,
) {
}

ngOnInit() {
  this.myService.StatusMission(this.ids)
}

two.component.ts(获取参数的组件)

myIds:any[];
subscription: Subscription;
constructor(
    private myService: MyService,
) {
}
ngOnInit) {
   this.subscription = this.myService.$status.subscribe(ids => {
   this.myIds=ids; (获取参数)
  });
}
ngOnDestroy() {
  this.subscription.unsubscribe();
}

方法二

MyService中

$loading: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
loading(): Observable<boolean> {
  return this.$loading.asObservable();
}
changeLoading(value: boolean): void {
  this.$loading.next(value);
}

one.component.ts(传递参数的组件)

this.myService.changeLoading(true);

two.component.ts(获取参数的组件)

this.myService.loading().subscribe((res) => {
   this.loading = res;
});
4.路由传值

1.在查询参数中传递数据

/product?id=1&name=2  =>  ActivatedRoute.queryParams[id]
[routerLink]="['/product']" [queryParams]="{id:1}"
this.routeInfo.snapshot.queryParams['id']

2.在路由的路径中传递数据

{path:/product/:id}  =>  /product/1  =>  ActivatedRoute.params[id]
[routerLink]="['/product',1]" 
this.routeInfo.snapshot.params['id']

3.在路由配置中传递数据

{path:/product,component:ProductComponent,data:[{isProd:true}]} => ActivatedRoute.data[0][isProd]

参数快照和参数订阅(subscribe)

this.routeInfo.snapshot.params['id'] //参数快照
this.routeInfo.params.subscribe((params:Params)=>{this.id=params['id']}) //参数订阅,解决相同页面改变参数的问题
5.存Session Storage(不推荐)

最后:

1. 组件间传值/路由传值/session stotage—页面刷新,数据不会丢失
2. service/订阅—页面刷新,数据会丢失 
3. 根据自己的需要选择不同的传参方式
Angular 中,组件间的父子可以通过输入属性(@Input)和输出属性(@Output)来实现。 1. 父组件向子组件(通过输入属性): - 在子组件的类中,使用 `@Input()` 装饰器定义一个输入属性,例如 `@Input() value: string;`。 - 在父组件的模板中,使用子组件的标签,并通过绑定属性的方式将递给子组件,例如 `<app-child [value]="parentValue"></app-child>`。 2. 子组件向父组件(通过输出属性和事件): - 在子组件的类中,使用 `@Output()` 装饰器定义一个输出属性,并创建一个事件发射器,例如 `@Output() valueChange: EventEmitter<string> = new EventEmitter<string>();`。 - 在子组件中的某个适当的时机,调用事件发射器的 `emit()` 方法来触发事件,并递需要递给父组件,例如 `this.valueChange.emit(newValue);`。 - 在父组件的模板中,使用子组件的标签,并绑定相应的事件处理函数来接收子组件发出的事件,例如 `<app-child (valueChange)="onChildValueChange($event)"></app-child>`。在父组件的类中,实现名为 `onChildValueChange()` 的事件处理函数来处理子组件递过来的。 通过上述方式,父组件和子组件之间可以进行简单和复杂的数据递,并实现双向通信。这种组件通信的方式可以有效地在 Angular 应用程序中递和共享数据,以实现组件之间的交互和协作。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值