angular 父组件和子组件

青春壹個敷衍的年華 提交于 2019-12-25 04:19:45

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

最终可看

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!