angular4中父组件如何传递子组件的方法
原文链接
https://blog.csdn.net/u012396955/article/details/78852140
- 子组件ts
export class ChildComponent implements OnInit {
constructor() { }
ngOnInit() {
}
greeting(name:string){
console.log('hello'+name);
}
}
- 父组件模板
<!--1.在控制器里用typescript代码实现-->
<app-child #child1></app-child>
<!--2.在模板上用模板变量实现-->
<app-child #child2></app-child>
<button (click)="child2.greeting('**Jerry**')">按钮调用child2的greeting方法</button>
- 父组件调用
export class AppComponent implements OnInit{
@ViewChild('child1')
child1:ChildComponent;
ngOnInit(): void {
this.child1.greeting('*tom*');
}
}
- 结果
hello *tom*
hello **jerry**
子组件传递父组件
原文链接
https://blog.csdn.net/qq_36547601/article/details/84345080
- 父组件实现test()方法
- 在插座中自定义一个事件
- 子组件通过@Output()实现一个自定义事件
- 子组件调用该自定义事件的方法
父组件ts
test(){
alert('我是父组件的alert方法')
}
父组件html
<app-child (test)='test()'></app-child>
子组件ts
@output() test = new ElementRef();
doFatherMethod(){
this.test.emit();
}
父子组件传值@input@output @ViewChild
原文链接
https://blog.csdn.net/u013318615/article/details/78963060
ViewChild主动获取数据
//在子组件中引入viewchild
import { ViewChild } from '@angular/core';
@ViewChild("index") index;
// html中引用组件
<app-index #index></app-index>
<button (click)="parentClick()">调用index中的方法</button>
// ts文件中使用子组件的方法和数据
parentChild()
{
this.index.childRun();
}