Angular学习之旅-----父子组件传值二@ViewChild

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

================================================================================================

@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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑞朋哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值