父组件通过局部变量获取子组件的引用 ,主动获取子组件的数据和方法
================================================================================================
@ViewChild让父组件来获取子组件的方法
1.调用子组件给子组件定义一个名称
2. 引入 ViewChild
3. ViewChild 和刚才的子组件关联起来
4.调用子组件
1. 定义cart组件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
public msg="我是子组件的数据"
constructor() { }
ngOnInit() {
}
run(){
alert('这是购物车子组件的方法')
}
}
2. 父组件调用子组件的时候给子组件起个名字
<div>
<h2>这是商品组件</h2>
<button (click)="cart.run()">父组件执行子组件的方法</button>
<button (click)="getChildData()">父组件调用自己的方法获取子组件的数据</button>
<hr>
<app-cart #cart></app-cart>
</div>
import { Component, OnInit,ViewChild } from '@angular/core';
import { CartComponent } from '../cart/cart.component';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
@ViewChild('cart') cart; // 定义子组件,注意括号里的东西和#cart对应起来
constructor() { }
ngOnInit() {
}
getChildData() {
this.cart.run()
// 获取子组件的数据
// alert(this.cart.msg)
this.cart.msg="我是父组件改变子组件cart数据后的msg"
}
}
<div>
<h2>这是购物车组件---{{msg}}</h2>
</div>