本文介绍了从Angular 4中的另一个组件访问组件方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个仪表板组件,一个头部组件和一个userOverview组件.

I have a dashboard component, a head component, and a userOverview component.

仪表板组件.ts文件

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

userOverview组件.ts文件

userOverview component .ts file

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

标题组件.html文件

header component .html file

<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()绝对行不通.

Now I am able to get this.name when navigate to different component, but I know by using this.name.startTour() is definitely not going to work.

感谢任何提示或解决方案.

Thanks for any hints or solutions.

推荐答案

如果组件是独立的,则 cannot 就像这样调用.如果component1和component2是同级,则可以使用 EventEmitter @Input

You cannot just call like that if the components are independent.If component1 and component2 are siblings you can use EventEmitter @Input

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

You can use also use a Shared service with subject. A service in Angular is a singleton, meaning it is managed as a single instance. So if each of the components access the service, they will access the same shared data.

这篇关于从Angular 4中的另一个组件访问组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 16:23