美文网首页
Angular 8 父子组件之间通信(简单易懂)

Angular 8 父子组件之间通信(简单易懂)

作者: 阿秃 | 来源:发表于2020-01-10 14:06 被阅读0次

    父组件给自组件传值 - @input

    父组件不仅可以给子组件传递简单的数据,还可以把自己的方法以及整个父组件传给子组件

    传递数据

    父组件调用子组件的时候传入数据

    父组件文件 app.component.html
    <app-header [msg]="msg"></app-header>
    
    

    子组件引入Input模块

    //子组件文件 header.component.ts
    
    import { Component, OnInit, Input } from '@angular/core';
    
    

    子组件中@Input 接受父组件传过来的数据

    //子组件文件 header.component.ts
     @Input() msg:string
    

    子组件显示父组件传入的数据

    子组件文件 header.component.html
    <div>{{msg}}</div>
    

    以上就完成了简单的父组件向子组件传值,接下来看看事件的传递

    子组件执行父组件的方法

    父组件调用子组件的时候传入方法

    // 父组件文件 app.component.html
    <app-header [msg]="msg" [close]="close"></app-header>
    // 在父组件中定义好close具体作用
    // 父组件文件 app.component.ts
    close(){
        console.log("这里是关闭函数")
    }
    

    子组件@Input接收父组件传入的方法

    //子组件文件 header.component.ts
    @Input() close:any;
    //并且在相应的事件中触发由父组件传入的方法
    closeCurrent(){
        this.close()
    }
    

    子组件页面触发事件的DOM

    //子组件文件 header.component.html
    
    <div (click)="closeCurrent()">关闭</div>
    
    

    以上就是简单的父组件向子组件传递自己的方法,接下来是将整个父组件传递给子组件

    将整个父组件传递给子组件

    在父组件调用子组件的时候 将this传给子组件, this指向就是整个父组件实例

    //父组件文件 app.component.html
    <app-header [msg]="msg" [close]="close" [parent]="this"></app-header>
    
    

    在子组件中@Input接收父组件传入的this [xxx]="this" 这里的xxx是自定义的,只要在子组件中接收的一样 就可以了

    //子组件文件 header.component.ts
    @Input() parent:any
    //子组件中就可以调用父组件的方法和变量了
    this.parent.close()
    

    帮到你的话 点个赞吧

    相关文章

      网友评论

          本文标题:Angular 8 父子组件之间通信(简单易懂)

          本文链接:https://www.haomeiwen.com/subject/lrudoctx.html