位置:首页 > web前端 > angular

angular父组件执行子组件的方法 获取子组件数据

dearweb 发布:2021-08-25 22:29:30阅读:

angular父组件如何执行子组件的方法,获取子组件数据

父组件里面的代码

<p>我是父组件</p>
<hr>
<app-child #child></app-child>
<hr>
<button (click)="getChildData()">获取子组件的数据</button>

<hr>
<button (click)="getChildRun()">执行子组件的run方法</button>

父组件TS代码

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

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

  @ViewChild('child') child:any
  @ViewChild('child') run:any
  constructor() { }

  ngOnInit(): void {
  }
  // 获取子组件数据
  getChildData(){
    console.log(this.child.msg) //我是子组件
  }
//执行子组件的额run方法
  getChildRun(){
    console.log(this.child.run()) //我是子组件run()方法
  }
}

子组件TS代码

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
  public msg:string = "我是子组件"
  constructor() { }

  ngOnInit(): void {
  }

  run(){
    console.log('我是子组件run()方法')
  }
}

上面就是父组件获取子组件数据和方法的基本用法。

24人点赞 返回栏目 提问 分享一波

小礼物走一波,支持作者

还没有人赞赏,支持一波吧

留言(问题紧急可添加微信 xxl18963067593) 评论仅代表网友个人 留言列表

暂无留言,快来抢沙发吧!

本刊热文
网友在读
手机扫码查看 手机扫码查看