【问题标题】:How to inject a component instance in angular2如何在angular2中注入组件实例
【发布时间】:2016-02-20 15:51:17
【问题描述】:

假设我想实现一个灯箱组件,它使用<dialog> 来呈现其内容。比如:

@Component({
  selector: 'image-popup',
  template: `
  <dialog>
  ...
  </dialog>
`
})
export class ImagePopupComponent {
...
  show(): void {
    this.element.nativeElement.showModal();
  }
}

如果我在主应用程序组件中创建它的一个实例,我如何才能从其他组件访问它。例如,在某些后代组件中,我有一个按钮,我希望单击该按钮以触发此对话框实例上的 show()。在我的用例中,这个组件会有一个 imageUrl 属性,同一个组件会被多次使用来展示不同的图片。

【问题讨论】:

  • 使用共享服务。有大量类似的问题有答案。
  • Martin 下面的评论看起来是正确的。请注意,默认情况下服务注入是单例的。因此,您将在所有组件中收到相同的“MyModalService”实例。

标签: angular


【解决方案1】:

您可以为此使用服务。

@Injectable()
export class MyModalService {
    component: MyModal;
}

@Component({
    selector: 'my-modal',
})
export class MyModal {
    constructor(private element: ElementRef, modalService: MyModalService) {
        modalService.component = this;
    }

    show(): void {
        this.element.nativeElement.showModal();
    }
}

然后在其他一些组件中:

@Component({
    selector: 'another',
})
export class AnotherComponent {
    constructor(private _modalService: MyModalService) {
    }

    buttonClicked() {
        this._modalService.show();
    }
}

【讨论】:

  • 使用这个方法,MyModal模板会自动渲染吗?例如,如果 MyModal 使用 bootstrap modal,而我使用 this.element.nativeElement.modal(),bootstrap modal 会自动出现吗?
猜你喜欢
  • 2017-02-13
  • 1970-01-01
  • 2017-04-16
  • 2017-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多