Angular 父组件通过@ViewChild 主动获取子组 件的数据和方法

1. 创建2个组件:footer(子组件) & news(父组件)

ng g component components/footer
ng g component components/news

2. 调用子组件给子组件定义一个名称

在这里插入图片描述
news.component.html

<!--  调用子组件给子组件定义一个名称 -->
<app-footer #footer></app-footer>
<br>
<hr>
<br>
<div>我是一个新闻组件</div>
<button (click)="getChildMsg()">获取子组件的msg</button>
<br>
<br>
<button (click)="getChildRun()">执行子组件的run方法</button>

2. 引入 ViewChild&ViewChild 和刚才的子组件关联起来

在这里插入图片描述
news.component.ts

// 引入 ViewChild
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 和刚才的子组件关联起来
  @ViewChild('footer') footer: any;

  constructor() {
    
    }

  ngOnInit() {
    
    }

  getChildMsg() {
    
    
    //获取footer子组件的数据
    alert(this.footer.msg);
  }

  getChildRun() {
    
    
    this.footer.run();
  }
}

3. 定义子组件

在这里插入图片描述
footer.component.html

<h2>我是footer子组件</h2>

在这里插入图片描述
footer.component.ts

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

@Component({
    
    
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.css'],
})
export class FooterComponent implements OnInit {
    
    
  public msg = '我是子组件footer的一个msg';

  constructor() {
    
    }

  ngOnInit() {
    
    }

  run() {
    
    
    alert('我是子组件的run方法');
  }
}

4.调用子组件

在这里插入图片描述
news.component.html

<app-footer #footer></app-footer>
<br>
<hr>
<br>
<div>我是一个新闻组件</div>
<button (click)="getChildMsg()">获取子组件的msg</button>
<br>
<br>
<button (click)="getChildRun()">执行子组件的run方法</button>

5. 根组件引入父组件

在这里插入图片描述
app.component.html

<app-news></app-news>

6. 运行程序

命令行输入:

ng serve --open

运行结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


猜你喜欢

转载自blog.csdn.net/I_r_o_n_M_a_n/article/details/114988365