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>

猜你喜欢

转载自blog.csdn.net/qq_43579525/article/details/83961341