子组件通过@Output触发父组件的方法
dearweb
发布:2021-08-25 22:42:14阅读:
子组件通过@Output触发父组件的方法
子组件引入Output,EventEmitter
import { Component, OnInit,Output,EventEmitter } from '@angular/core';
子组件实例化 EventEmitter
// 用EventEmitter 和 output 装饰器配合使用 <string> 指定类型
// @Output() private outer = new EventEmitter<string>
// 子组件通过EventEmitter 对象 outer 实例广播数据
// this.outer.emit('msg from child')
// 父组件调用子组件的时候,定义接收事件,outer就是子组件的EventEmitter 对象 outer
<app-header (outer)="runParent($event)"></app-header>子组件代码
<button (click)="sendParent()">通过@output给父组件广播数据</button>
import { Component, OnInit,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
@Output() public ourter = new EventEmitter()
public msg:string = "我是子组件"
constructor() { }
ngOnInit(): void {
}
sendParent(){
this.ourter.emit('我是子组件的数据')
console.log(this.ourter)
}
}父组件代码
<button (ourter)="getChildDataOurter($event)">接收子组件ourter传值</button>
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-father',
templateUrl: './father.component.html',
styleUrls: ['./father.component.scss']
})
export class FatherComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
//getChildDataOurter
getChildDataOurter(e:any){
console.log(123)
console.log(e) //子组件给父组件广播的数据
}
}如果你学了vue的事件总线,相信这里学起来不会很难
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧