typescript - Angular 2 : Call existing component from another component

标签 typescript angular

我正在使用路由功能创建一个带有 Angular 2 的应用程序,并且我有一个由更高层路由之一呈现的弹出组件,我想在呈现的组件中的单击事件上打开它通过其中一条更深的路线。

例如,假设我有一个带有包含弹出窗口的模板的基本路由器:

@Component({
    selector: 'application',
    template: '<router-outlet></router-outlet><popup-component></popup-component>',
    directives: [PopupComponent]
})
@RouteConfig([
    { ... },
    { ... }
])
export class AppRoute { }

还有一个带有 open 方法的简单弹出组件:

@Component({
    selector: 'popup-component',
    template: '<div [class.show]="isVisible">This is a popup.</div>'
})
export class PopupComponent {
    public isVisible: boolean = false;
    show() {
        this.isVisible = true;
    }
}

如何在 AppRoute 已从位于路由树下方某处的另一个组件呈现的特定 PopupComponent 上调用此 show 方法?

我试过像这样使用依赖注入(inject):

@Component({
    selector: 'my-component',
    template: '<button (click)="showPopup()"></button>'
})
export class MyComponent {
    constructor(private popup: PopupComponent) { }
    showPopup() {
        this.popup.show();
    }
}

但这只是创建了一个尚未实际呈现的 PopupComponent 的新实例。如何调用 AppRoute 呈现的那个?

最佳答案

你需要一个共享服务

import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Rx';
export class PopupService{
   show:Subject<boolean> = new Subject();
}

将服务添加到 AppRoute 中的提供者

@Component({
    providers:[PopupService],
    selector: 'application',
    ...
])
export class AppRoute { }

将服务注入(inject)popup-component并订阅节目主题。

@Component({
    selector: 'popup-component',
    template: '<div [class.show]="isVisible">This is a popup.</div>'
})
export class PopupComponent {
    public isVisible: boolean = false;
    constructor(private popup: PopupService) {
      popup.show.subscribe( (val:boolean) => this.isVisible = val );
    }
}

将它注入(inject)任何你想显示弹出窗口的组件,在show主题上调用next

@Component({
    selector: 'my-component',
    template: '<button (click)="showPopup()"></button>'
})
export class MyComponent {
    constructor(private popup: PopupService) { }
    showPopup() {
        this.popup.show.next(true);
    }
}

关于typescript - Angular 2 : Call existing component from another component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36456564/

相关文章:

angular - 如何从 Angular 组件中的服务获取字符串值?

typescript - 流类型可以在方法链中加强实例的方法定义吗

angular - 如何从返回 JSON 数组的 Angular http get 填充 html 表

angular - 收到错误 : "Has no exported member AngularFire, AuthProviders, AUthMethods, FirebaseListObservable" in AngularFire2?

Angular 循环遍历数组并使用 forkJoin 收集 Observables

google-chrome - Angular 2. Chrome : Cannot find control with unspecified name attribute 错误

javascript - @reduxjs/toolkit 和 Typescript 出错 - TS1005

javascript - 在RxJS中,为什么要检查toSubscriber中的rxSubscriberSymbol?

angular - 使用 ngx-translate 本地化 Angular 库

angular - Electron 无法工作的Angular2路线