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)到其他订阅的组件中。
剪藏链接:
本文来自博客园,作者:77工作室,转载请注明原文链接:https://www.cnblogs.com/z7luv/p/15672569.html
如果您觉得阅读本文对您有帮助,请点击一下右下方的推荐按钮,您的推荐将是我写作的最大动力!版权声明:本文为博主原创或转载文章,欢迎转载,但转载文章之后必须在文章页面明显位置注明出处,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了