angular 父子组件通信
1. 子组件调用父组件的方法和数据 -- Input 装饰器
1. fatherComponent.html中
toChildStr -- 父组件中定义的数据
fatherMethod -- 父组件中的方法
fatherComponent -- 父组件本身, this指代父组件实例,通过 [fatherCompoent] 将父组件实例传递给子组件
<childComponent #login [toChildStr]="toChildStr" [fatherMethod]="fatherMethod" [fatherComponent]="this"></app-login>
2. childComponent.ts 中
通过 @Input 装饰器获取父组件属性,方法,父组件实例
export class LoginComponent implements OnInit {
@Input() toChildStr: string -- 父组件属性
@Input() fatherMethod:any -- 父组件方法
@Input() fatherComponent: any -- 父组件实例
constructor() { }
ngOnInit() {
}
getFatherComponentMethod() {
alert(this.toChildStr) -- -- 父组件属性
alert(this.fatherComponent.toChildStr) -- -- 父组件实例获取父组件属性
this.fatherComponent.fatherMethod() -- -- 父组件实例调用父组件方法
this.fatherMethod() -- -- 父组件方法
}
}
2. 父组件调动子组件的方法和数据 -- ViewChild装饰器
1. fatherComponent.html中
通过#var 方式给子组件标记
<childComponent #child></childComponent>
2. fatherComponent.ts中
通过@ViewChild()装饰器获取子组件实例
@ViewChild('child', null) childComponent: any
userChildMethod() {
// 调用子组件方法 -- 获取属性同样写法
this.childComponent.childMethod()
}
3. 通过事件触发器,子组件给父组件传参。即父组件获取子组件数据
以上两种方式都是主动获取数据或者方法。这种方式通过 EventEmitter 和 outPut 方式相当于,通过事件,子组件广播数据给父组件,父组件被动接受参数。
1. childComponent.ts
import { Output, EventEmitter } from '@angular/core';
export class LoginComponent implements OnInit {
@Output() outer:any = new EventEmitter() -- 声明并且输出一个事件触发器
public msg = "123"
public obj = {
num: 1
}
sendParent() {
this.outer.emit(this.obj) -- 通过事件触发器,发送数据给父组件
}
2. childComponent.html
<h5>通过事件触发器,子组件向父组件广播数据</h5>
<button (click)="sendParent()">数据发送给父组件</button>
3. parentComponent.html,
通过 (事件触发器)= “方法” 的方式监听子组件发出父消息。 (事件触发器) 必须与子组件中定义的名称一致
<childComponent (outer)="onReciveChildMsg($event)"></childComponent>
4. parentComponent.ts
通过方法获取传递的参数 $event
onReciveChildMsg(e) {
alert(e.num)
e.num = 2
// e = "456"
// this.msg = e
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)