Angular系列 -> 父子传值

发布时间 2023-04-22 16:36:07作者: 77工作室

1. parent to child: 

parent: 

<app-child [childMessage]="parentMessage"></app-child>

child:

@Input() childMessage: string;

2. child to parent:

@ViewChild : 使父组件可以获取到子组件的属性和功能;但是,子组件直到视图初始化完成后才可用,这就意味着我们需要在AfterViewInit 生命钩子中获取来自子组件的数据;

3. child to parent: 

@Output() and EventEmitter 

另一种在父子组件共享数据的方式是,从子组件发送数据,由父组件进行监听。这种方法适用的场景,主要发生在像button 点击或其他的用户事件, 需要共享数据的变化这种情况下;

parent:

创建一个方法去接收来自子组件的数据,无论什么时候事件发生,都会触发这个接收数据的方法;

import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    Message: {{message}}
    <app-child (messageEvent)="receiveMessage($event)"></app-child>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  constructor() { }

  message:string;

  receiveMessage($event) {
    this.message = $event
  }
}

child: 
用@Output()装饰器来声明一个变量,类型为 event emiter; 创建一个方法,发送带有message 数据(或我们想要发送的数据)的event,调用emit() 方法;然后创建个button 去触发这个创建的方法;

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
      <button (click)="sendMessage()">Send Message</button>
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  message: string = "Hola Mundo!"

  @Output() messageEvent = new EventEmitter<string>();

  constructor() { }

  sendMessage() {
    this.messageEvent.emit(this.message)
  }
}

4. shared service from different component

假如传递数据的组件没有直接的关系,我们可以用到 RxJS BehaviorSubject 。

  • It will always return the current value on subscription - there is no need to call onnext
  • It has a getValue() function to extract the last value as raw data.
  • It ensures that the component always receives the most recent data.

 例如: 创建一个公用的service,在service里创建一个BehaviorSubject,在需要获取此值的组件中订阅它,如果有新的值出现,则它就会自动广播(broadcast)到其他订阅的组件中。

 

剪藏链接: