angular - 从 Angular 4 中的另一个组件访问组件方法

标签 angular

我有一个仪表板组件、一个 head 组件和一个 userOverview 组件。

仪表板组件.ts文件

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

userOverview组件.ts文件

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

header 组件.html 文件

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

header 组件.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() 肯定行不通。

感谢您提供任何提示或解决方案。

最佳答案

如果组件是独立的,您不能就这样调用。如果组件1和组件2是兄弟,您可以使用 EventEmitter @Input

您还可以使用带有主题的共享服务。 Angular 中的服务是单例的,这意味着它作为单个实例进行管理。因此,如果每个组件都访问该服务,它们将访问相同的共享数据。

关于angular - 从 Angular 4 中的另一个组件访问组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52508931/

相关文章:

angular - 没有 NgModel 的提供者! (Typeahead -> NgModel) 将 ngControl 添加到 bootstrap 4 TypeHead angular 2 时出现异常

javascript - RxJS(和 Angular ): Attempting to cache one-time HTTP requests still causes multiple requests

javascript - 如何重构检查数组长度的长 if-else 语句?

angular - 从可观察到的填充表单 - Angular2

angular - Angular 中是否有类似 APP_INITIALIZER 的延迟加载模块?

angular - Kendo UI Angular 2 中网格列名称的工具提示

调用了 Angular ngrx + Firebase OAuth 操作但没有效果

javascript - 我如何显示 GroupLists 的 FormArray?

angular - 父组件的值不会被子组件改变

Angular2 - cloudfoundry 上的 Nginx 路由 404 错误