【问题标题】:Angular 2: Call existing component from another componentAngular 2:从另一个组件调用现有组件
【发布时间】:2016-04-06 16:09:54
【问题描述】:

我正在使用路由功能创建一个带有 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 方法?

我尝试过像这样使用依赖注入:

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

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

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    您需要共享服务

    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 { }
    

    将服务注入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 );
        }
    }
    

    将其注入到您要显示弹出窗口的任何组件中,在 show 主题上调用 next

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

    【讨论】:

      猜你喜欢
      • 2016-09-28
      • 2017-09-07
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2018-11-30
      相关资源
      最近更新 更多