Angular父子组件的方法传递以及数据传递

备注:这里父组件是news,子组件是footer

父组件->子组件

  1) 子组件引入装饰器

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

  2) 父组件传值

<app-header [title]="title"></app-header>  

  3) 子组件接收

@Input() title:string;//接收传入的数据

  4) 除了值,也可传递方法,或将整个组件传递给子组件 

 <app-header [title]="title" [run]="run" [home]="this"></app-header>

子组件->父组件

1) 使用ViewChild获取子组件数据或方法

2) 使用@Output和EventEmitter触发父组件的方法

i.子组件引入-----

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

ii.子组件实例化output对象--------

@Output() private outer=new EventEmitter();

iii. 子组件广播数据(按钮触发)

sendParent():void{

    // alert(11);

 this.outer.emit("我是子组件数据");//广播

 }

iv. 父组件接收数据,并调用get方法------

<app-foo (outer)="get($event)"></app-footer>

  完整代码:

父组件:

html

<p>news works!</p>
<button (click)="getData()">获取子组件的数据</button>
<button (click)="run()">获取子组件的方法</button>
<app-footer #footer (outer)="get($event)"></app-footer>

  TS

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

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
  @ViewChild('footer') footer:any;
  constructor() { }

  ngOnInit(): void {
  }
  getData():void{
    alert(this.footer.msg);
  }
  run():void{
    this.footer.run();
  }
  get(e):void{
    alert("父组件收到广播,执行get方法");
    alert(e);//子组件广播的数据
  }
}

子组件:

html

<p>footer works!</p>
<button (click)="sendParent()">通过output广播数据</button>

  TS

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

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {
  public msg:string="footer message";
  constructor() { }
  @Output() private outer=new EventEmitter();
  ngOnInit(): void {
  }
  run():void{
    alert("footer run!");
  }

  sendParent():void{
    // alert(11);
    this.outer.emit("我是子组件数据");//广播
  }
}