Angular组件传值

  1. 父组件传给子组件, 可以传data, function, self自身

//父组件
<app-header [title]="title" [msg]="msg" [run]="run" [home]="this">
</app-header>
<div>
    <p>home</p>
</div>


//子组件
/*
 * @Author       : G.F
 * @Date         : 2020-05-13 20:45:05
 * @LastEditTime : 2020-05-16 23:24:56
 * @LastEditors  : G.F
 * @FilePath     : /angularproject/src/app/components/header/header.component.ts
 * @Description  : 
 */ 
import { Component, OnInit, Input } from '@angular/core';

export class HeaderComponent implements OnInit {

  //接收父组件传来的数据
  @Input() title:any;
  @Input() msg:any;
  // 传入function
  @Input() run:any;
  // 传入父组件自身,this 绑定的
  @Input() home:any;

  constructor() { }

  ngOnInit(): void {
  }

  getParentMsg(){
    //  alert(this.msg)
    alert(this.home.msg)

  }

  getParentRun(){
    // this.run()
    this.home.run()
 }

}

2. 父组件接收子组件data and function

1 ViewChild  方法

//父组件
<app-header [title]="title" [msg]="msg" [run]="run" [home]="this" #headerChild>
</app-header>
<div>
    <p>home</p>
    <button (click)="getChild()">父组件获取子组件的data</button>
    <button (click)="getChildFun()">父组件获取子组件的function</button>

</div>


/*
 * @Author       : G.F
 * @Date         : 2020-05-13 20:30:38
 * @LastEditTime : 2020-05-17 10:52:30
 * @LastEditors  : G.F
 * @FilePath     : /angularproject/src/app/components/home/home.component.ts
 * @Description  : 
 */ 
import { Component, OnInit, ViewChild } from '@angular/core';
import { log } from 'util';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  @ViewChild('headerChild') headerChild:any;

  constructor() { }

  ngOnInit(): void {
  }

  getChild(){
    console.log(this.headerChild.message)
  }

  getChildFun(){
    this.headerChild.messageFun()  

  }

}

2 @Output 和 EventEmitter获取 

//子组件
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
 
//子组件引入装饰器
 
@Output() private outer = new EventEmitter();
 
//定义@Output的装饰器
 
emitData() {
 
    this.outer.emit('子组件的data');
 
}
 
//子组件emit给父级的方法, 点击触发
 
<button (click)="emitData()">提交数据给父级</button> 



//父组件里的子组件
<app-header (outer)="getChildMsg($event)"></app-header>
 
//父级通过outer事件接受,参数是$event, outer必须和子组件定义的变量名一致
 
getChildMsg(msg) {
 
  console.log(msg, '子组件data');
 
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值