Angular中父组件获取子组件的数据、方法by @ViewChild

现有一个父组件app-news,一个子组件app-footer,现在想要在父组件中访问子组件中的数据和方法,实现方案如下。

1.子组件中的定义

定义被访问的变量和方法,完整代码如下:

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

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

  // 将要被父组件访问的变量
  public message:string='这里是footer组件的数据';

  constructor() { }
  ngOnInit(): void {}

  // 将要被父组件访问的方法
  run(){
    console.log('这里是footer组件的方法');
  }
}

2.父组件中的定义:


(1)在Html 模板中增加定义:

<app-footer #footer></app-footer>
<p>这里是新闻组件</p>
<button (click)="getChildData()">获取子组件的数据</button>
<button (click)="getChildMethod()">获取子组件的方法</button>

这里的<app-footer #footer></app-footer> #footer是给子组件起一个名字 

(2)引入ViewChild:

import { ViewChild } from '@angular/core';

(3) 定义绑定变量

@ViewChild("footer") footer:any;

(4)定义模板中需要的方法:
 

  getChildData(){
    console.log('子组件的数据:'+this.footer.message);
  }

  getChildMethod(){
    console.log('子组件的方法');
    this.footer.run();
  }

父组件的完整代码:

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

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

  
  @ViewChild("footer") footer:any;

  constructor() { }

  ngOnInit(): void {
  }

  getChildData(){
    console.log('子组件的数据:'+this.footer.message);
  }

  getChildMethod(){
    console.log('子组件的方法');
    this.footer.run();
  }

}

3.测试

 打开浏览器访问http://127.0.0.1:2400

点击【获取子组件的数据】会在浏览器控制台输出:
子组件的数据:这里是footer组件的数据

点击【获取子组件的方法】会在浏览器控制台输出:

子组件的方法
footer.component.ts:22 这里是footer组件的方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值