angular 父组件和子组件

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();
}

最终可看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值