1. 1 . 父组件中 加入子组件的名字标签
    2. 2. 给子组件一个名字,
    3. 3. 在父组件中 通过viewChild去获取到子组件的方法,通过.去调用子组件的方法
    1. html文件中
    2. <app-nav #nav></app-nav>
    3. <!-- 结点的名字 #开头 -->
    4. <div #box>
    5. dom节点
    6. </div>
    7. 子组件中定义一个run方法
    8. run(){
    9. console.log('this is nav-run')
    10. }
    11. ts文件中
    12. import { Component, OnInit,ViewChild } from '@angular/core';
    13. @Component({
    14. selector: 'app-news',
    15. templateUrl: './news.component.html',
    16. styleUrls: ['./news.component.less']
    17. })
    18. export class NewsComponent implements OnInit {
    19. // @ViewChild('在html文件中以#开头的名字') 赋值给Box:any;
    20. @ViewChild('box') Box:any;
    21. @ViewChild('nav') nav:any
    22. constructor() { }
    23. ngOnInit() {
    24. }
    25. ngAfterViewInit(): void {
    26. //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
    27. //Add 'implements AfterViewInit' to the class.
    28. console.log(this.Box.nativeElement);
    29. this.Box.nativeElement.style.color = 'red'
    30. console.log(this.nav.todolist);
    31. this.nav.run()
    32. //nav组件中所有定义的的方法都可以通过this.nav获取到
    33. }
    34. }