angular组件间的信息传递

原文

  https://www.jianshu.com/p/82207f2249c1

大纲

  1、父组件向子组件传递信息:通过属性
  2、子组件向父组件传递信息:通过事件
  3、父组件获取子组件的信息:通过调用模板引用变量
  4、父组件和子组件共享信息:通过服务共享信息
  5、父组件获取子组件的信息:通过@ViewChild 或@ContentChild
  6、参考代码

父组件向子组件传递信息:通过属性

//父组件向子组件通过属性传递信息
<app-childen [data]="parent_data"></app-childen>
//子组件通过@Input接受信息
@Input() data: string;

子组件向父组件传递信息:通过事件

//子组件传递信息给父组件
@Output() event = new EventEmitter();
private name: string;
upward() {
  /**
  * 实例化EventEmitter,赋值给event,event被@Output装饰器定义为输出属性,
  * 这样event具备了向上级传递数据的能力,通过调用EventEmitter类中定义的emit方法,
  * 来向上传递数据
  */
  this.event.emit(this.name);
}

//父组件通过事件接收子组件外传的信息
<app-childen2 (event)="getData($event)"></app-childen2>

getData(event: any) {
  this.parent_name = event;
}

父组件获取子组件的信息:通过调用模板引用变量

  通过@Input和@Output可以实现数据之间的传递,但是无法获取子组件的类属性和类方法,接下来我们通过局部变量方式实现获取子组件其他成员。
  通过#号来标识一个变量, 这样在父组件模板中创建了一个局部变量#chiden来获取子组件的实例,调用子组件中的方法和属性。

//在子组件中加上模板引用变量,方便父组件调用属性方法
<app-childen3 #chiden></app-childen3>

//父组件通过子组件的模板引用变量来调用子组件的属性和方法
<input type="button" 
    value="调用子组件方法" (click)="chiden.fun1()"
>
<input type="button" 
    value="调用子组件属性" (click)="getChildInfo(chiden.childInfo)"
>

父组件和子组件共享信息:通过服务共享信息

  父子组件共享同一个服务,利用该服务实现双向通信

父组件获取子组件的信息:通过@ViewChild 或@ContentChild

  @ViewChild的作用是声明对子组件元素的实例引用,意思是通过注入的方式将子组件注入到@ViewChild容器中,你可以想象成依赖注入的方式注入,只不过@ViewChild不能在构造器constructor中注入,因为@ViewChild会在ngAfterViewInit()回调函数之前执行。

import {Component, ViewChild} from '@angular/core';
import {ChildenComponent} from './child.component';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent {
  @ViewChild(ChildenComponent) child: ChildenComponent;

  OnClick() {
    this.child.fun1();
  }
}

 参考代码

  angular实例代码中的angular-transfer-info中有我以上描述的代码实例,如果有需要可以从里面下载或者运行,希望能对读者有所帮助。

原文地址:https://www.cnblogs.com/shcrk/p/9219072.html