Angular中父子组件传值@Input @Output @ViewChild最全面最简单的总结

父组件传递给子组件:

值传递方式:@Input既可以传递数据也可以传递方法

  • 传递数据(不举例了)
  • 传递方法
// 父组件定义方法
parentRun(){
    alert('这是父组件的 run 方法');
}

调用子组件时传入当前方法(是传递方法不是调用方法)

<app-header [msg]="msg" [run]="parentRun"></app-header>

子组件接收和使用父组件传过来的方法

import { Component, OnInit ,Input } from '@angular/core';

export class HeaderComponent implements OnInit {
   
    @Input() msg:string 
    @Input() run:any; // 接收父组件传递过来的方法parentRun
    
    constructor() { } 

    ngOnInit() {
        this.run(); // 子组件调用父组件的parentRun方法
    }

}

子组件传递给父组件:

1、事件传递方式:@Output + EventEmitter事件传递的方式

子组件实例化装饰器修饰的EventEmitter实例,并在需要的时候发出传递事件的信号(可以传参)

import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
 
export class HeaderComponent implements OnInit {

    // 用EventEmitter和Output装饰器配合使用,<string>指定广播传递的参数类型变量
    @Output() private outer = new EventEmitter<string>(); 
    
    sendParent(){
        this.outer.emit('msg from child'); // 广播传递数据给父组件
    }

}

父组件调用子组件的时候,定义接收事件 , outer就是子组件的EventEmitter对象outer

<!--一旦接收到子组件发出的事件传递信号后就会执行父组件中定义好的接收方法-->
<app-header (outer)="runParent($event)"></app-header> 


// 接收子组件传递过来的数据 
runParent(msg:string){
    alert(msg); 
}

2、主动获取:父组件通过局部变量获取子组件的引用,主动获取子组件的数据和方法

子组件定义如下:

export class FooterComponent implements OnInit { public msg:string;
    public msg: string;

    constructor() { } 
    
    ngOnInit() {} 

    footerRun(){
        alert('这是footer子组件的Run方法');
    }
}

父组件调用子组件的时候给子组件取个id标识

<app-footer #footer></app-footer>

2.1、可在页面上直接获取执行子组件的方法

<button (click)='footer.footerRun()'>获取子组件的数据</button>

2.2、在控制器controller中通过@ViewChild,引入为成员变量

import { Component, OnInit ,ViewChild} from '@angular/core';

    @ViewChild('footer') footerChild; // 在父组件的控制器中引用子组件

    run(){
        this.footerChild.footerRun(); // 在父组件的控制器中调用子组件的方法或变量
    }

猜你喜欢

转载自blog.csdn.net/xfwdxt/article/details/82111016
今日推荐