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()方法')
}
}上面就是父组件获取子组件数据和方法的基本用法。
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧