angular父子传值

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

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

  • 1.父组件调用子组件的时候传入数据
<app-header [msg]="msg"></app-header>
    1. 子组件引入 Input 模块
import { Component, OnInit ,Input } from '@angular/core';
    1. 子组件中 @Input 接收父组件传过来的数据
export class HeaderComponent implements OnInit { 
@Input() msg:string
constructor() { } 
ngOnInit() { } 
}
  • 4 子组件中使用父组件的数据
<h2>这是头部组件--{{msg}}</h2>
<app-header [title]="title"  [msg]="msg" [run]='run' [home]='this'></app-header>
 import { Component, OnInit,Input} from '@angular/core';
  //接受父组件传来的数据
  @Input() title:any; 
  @Input() msg:any; 
  @Input() run:any; 
  @Input() home:any; 
 getParentRun(){
    //执行父组件的run 方法
    // this.run();
    alert(this.home.msg);
    this.home.run();
  }

子组件通过@Output 触发父组件的方法

  1. 子组件引入 Output 和 EventEmitter
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';

2.子组件中实例化 EventEmitter

@Output() private outer=new EventEmitter<string>(); 
/*用 EventEmitter 和 output 装饰器配合使用 <string>指定类型变量*/

3.子组件通过 EventEmitter 对象 outer 实例广播数据

sendParent(){ 
// alert('zhixing'); 
this.outer.emit('msg from child') 
}

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

<app-header (outer)="runParent($event)"></app-header>

5.父组件接收到数据会调用自己的 runParent 方法,这个时候就能拿到子组件的数据

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

父组件通过@ViewChild 主动获取子组 件的数据和方法

调用子组件给子组件定义一个名称
<app-footer #footerChild></app-footer>
引入 ViewChild
import { Component, OnInit ,ViewChild} from '@angular/core';
ViewChild 和刚才的子组件关联起来
@ViewChild('footerChild') footer;
调用子组件
run(){ 
this.footer.footerRun(); 
}
import { Component, OnInit,Output,EventEmitter } from '@angular/core';
@Output()  private  outer=new EventEmitter();
<button (click)="sendParent()">通过@Output给父组件广播数据</button>
 sendParent(){
    this.outer.emit('我是子组件的数据');
  }
<app-footer #footer  (outer)="run($event)"></app-footer>
  run(e){
    console.log(e);   //子组件给父组件广播的数据
    alert('我是父组件的run方法');
  }

四、非父子组件通讯

1、公共的服务
2、Localstorage (推荐)
3、Cookie

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容