簡體   English   中英

從Angular 4中的另一個組件訪問組件方法

[英]Access a component method from another component in Angular 4

我有一個儀表板組件,一個頭部組件和一個userOverview組件。

儀表板組件.ts文件

export class DashboardComponent implements OnInit {
    startTour() {
      // do something
    }
}

userOverview組件.ts文件

export class UserOverviewComponent implements OnInit {
    startTour() {
      // do something else
    }
}

標頭組件.html文件

<button (click)="openTour()"></button>

標頭組件.ts文件

export class HeaderComponent implements OnInit {
    openTour() {
                   // In here, I want to ask is there any way I could make a 
                   // call to  different component with the same method same.

      this.name = componentName // The component Name, such as
                                // DashboardComponent, UserOverviewComponent

      this.name.startTour(); // Something like this
    }
}

現在,我可以在導航到其他組件時獲取this.name,但是我知道通過使用this.name.startTour()絕對行不通。

感謝您提供任何提示或解決方案。

如果組件是獨立的,則cannot僅僅這樣調用。如果component1和component2是同級組件,則可以使用EventEmitter @Input

您還可以將共享服務與主題一起使用。 Angular中的服務是單例,這意味着將其作為單個實例進行管理。 因此,如果每個組件都訪問服務,則它們將訪問相同的共享數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM