angular父子组件传值

父组件到子组件

1.父组件传递数据

在父组件中调用子组件,通过[‘属性值’]进行传值

//父组件app-home,子组件app-header
//父组件中引用子组件,传递title及msg到子组件
<app-header [title]="title" [msg]="msg" [run]="run" [home]="this"></app-header>

2.子组件接受数据

//增加Input引用
import { Component, OnInit, Input } from '@angular/core';
//
//接收父组件传过来的数据
  @Input() title:any;
  @Input() msg:any;
  //接收方法
  @Input() run:any;
  //接收home组件的this
  @Input() home:any;

//在header中使用获取到的数据
<div>{{title}} --- {{msg}}</div>
getParentFunc(){
    this.run();
    console.log(this.home.title)
}

子组件到父组件

1.父组件根据ViewChild获取子组件实例

//父组件app-news 子组件app-top
//父组件中引用子组件
<app-top #top></app-top>
//定义获取子组件信息的方法
<button (click)="getChildMsg()">获取子msg</button>
<button (click)="getChildFunc()">获取子方法</button>

//父组件引用ViewChild
import {HttpClient,HttpHeaders} from '@angular/common/http'
//根据ViewChild获取子组件实例
@ViewChild('top') top:any;
//调用方法,可获取子组件的数据及方法
getChildMsg(){
    console.log(this.top.msg);
  }
  getChildFunc(){
    this.top.run();
  }

2.子组件通过广播的形式,向子组件发送数据

父组件app-news 子组件app-top

子组件操作

//子组件引用Output, EventEmitter
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
//获取引用实例
@Output() private outer = new EventEmitter();
//定义方法向父组件传值
setParent(){
    //向父组件传值
    this.outer.emit("我是子组件的数据")
  }

父组件接收

//在父组件中引用子组件,定义通过(outer)接收数据
<app-top #top (outer)="run($event)"></app-top>
//子组件广播时触发父组件方法,
run(event:any){
    //此处打印:我是子组件的数据
    console.log(event)
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值