Angular父组件获取子组件里的数据和方法

(父组件通过局部变量获取子组件的引用,主动获取子组件的方法)

1.在子组件里cart.component.ts里定义一个方法:

cartRun () {
	alert("这是购物车子组件里的方法")
}

2.在父组件produc.component.html里的子组件标签定义一个引用名字cart(让父组件识别调用)

<div class="parent">
	<button ></button>
	<app-cart  #cart></app-cart>
</div>

3.在父组件produc.component.html通过子组件定义的引用#cart来调用子组件cart.component.ts里的cartRun()方法

<div class="parent">
	<button  (click)="cart.cartRun()"></button>
	<app-cart #cart></app-cart>
</div>

(父组件通过局部变量获取子组件的引用,主动获取子组件里的数据)

1.父组件produc.component.ts里引入ViewChild

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

2.在父组件produc.component.html里的子组件标签定义一个引用名字#cart(让父组件识别调用)

<div class="parent">
	<button ></button>
	<app-cart  #cart></app-cart>
</div>

3.在父组件 produc.component.ts里通过@ViewChild()指定引用

export class NewComponent implements OnInit {
		//括号里的"cart"就是<app-cart  #cart></app-cart>里的#cart(一定要相同),另一个cart是指定类型
	 @ViewChild("cart") cart;
}  

4.在父组件produc.component.ts里定义getChildData()方法,并调用子组件cart.component.ts里的数据: public childData = “childData:父组件获取子组件的数据”;

getChildData(){
	// 获取子组件里的数据:public childData = "childData:父组件获取子组件的数据";
	//cart是上面 @ViewChild("cart") cart;里的cart,通过 this.cart.childData获取子组件里的数据
	 //alert(this.cart.childData)
	 //父组件里声明一个变量来接收数据
     this.fromChildData = this.cart.childData
     //console.log(this.fromChildData)
}

5.在父组件produc.component.html里

 <p>
    <button (click)='getChildData()'>
           父组件调用自己的方法获取子组件里的数据
    </button>
	
 </p>
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值