ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-11-30 16:34:38  阅读:222  来源: 互联网

标签:console log footer component 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组件的方法

标签:console,log,footer,component,ViewChild,中父,组件
来源: https://blog.csdn.net/weixin_38296425/article/details/121635515

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有