Angular系列 -> 父子传值

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)到其他订阅的组件中。

 

剪藏链接:

posted @   77工作室  阅读(117)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示