How to call router outlet child component method from parent comonent

前端 未结 10 2006
甜味超标
甜味超标 2020-12-18 19:42

I am new to angular2


    

I have a button in parent component, if

10条回答
  •  没有蜡笔的小新
    2020-12-18 19:52

    There are two ways to call router outlet child component method from the parent component.

    1. ViewChild/ViewChildren - You can use ViewChild/ViewChildren to get the element(s) or the directive(s) matching the selector from the view DOM. It doesn't matter child component is rendered by router outlet.

      import { ViewChild } from '@angular/core'; @ViewChild(HomeComponent) private childComponent: HomeComponent;

    Then you can call any method,

    this.childComponent.changeTitle();
    

    Demo - call router outlet child component method

    1. Shared services - Since angular services are singleton by injecting them to your controllers you can call methods. (Above answers are already mentioned this approach)

提交回复
热议问题