Angular 2中的组件如何通过调用其方法弹出另一个组件? [英] How can a component in Angular 2 pop up another component by invoking its method?

查看:56
本文介绍了Angular 2中的组件如何通过调用其方法弹出另一个组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设计了一个弹出组件,它旨在通过调用以下方法来显示和隐藏,这些方法设置了将其类绑定到的 back front 变量

I've designed a popup component and it's intended to show and hide by invokation of the following methods setting back and front variables that the class of it is bound to.

hide() {
  this.back = this.back.replace(/[ ]?shown/, "");
  this.front = this.front.replace(/[ ]?shown/, "");
}

show() {
  this.back += "shown";
  this.front += "shown";
}

问题是我希望弹出窗口可以从其他组件中调用,而不是它们的一部分.实际上,我针对的应用程序的标记如下.

The problem is that I wish the popup to be invokeable from other components, without it being a part of them. In fact, the markup for the application I'm aiming at is as follows.

<navbar></navbar>
<sidebar></sidebar>
<filter></filter>
<poppy></poppy>

不过,我不确定如何调用它.我对导航栏中的单击做出反应,并检测到该请求应该触发弹出窗口.

I'm not sure how to invoke it, though. I'm reacting to a click in the navigation bar and detecting that the request is supposed to trigger the popup to pop up.

if(notImplementedYet) {
  ???
}

我已经搜索了这个问题,但是我并没有真正清楚地了解解决该问题的正确方法.例如,我已经看过有关 Input Output

I've googled the issue but I'm not really getting a clear image of the proper way to approach it. For instance, I've seen something about Input and Output here but I can't judge if it's even remotely applicable for my need.

我还看到了

I also saw this but it doesn't tell me much, possibly due to lack of experience with Angular. Also, I worry that the parent-to-child/child-to-parent approach will result in a very nasty invokation structure.

推荐答案

您可以在要从中调用弹出窗口的组件中使用@Output.然后,您可以简单地使用模板变量在弹出组件中调用show或hide方法.

You can use @Output in the component from which you want to invoke the popup. You can then simply use template variable to invoke the show or hide methods in the popup component.

例如,当您在导航栏上单击以下代码时,可以显示弹出窗口:

For example, you can show your popup when clicking in nav bar by the code:

import { Component, Output, EventEmitter } from '@angular/core';
@Component({
    selector: 'navbar',
    templateUrl: './nav-bar.component.html'
})
export class NavComponent {
    @Output() onClickNav: EventEmitter<any> = new EventEmitter(); 
    onClick():void {
        this.onClickNav.emit(null);
    }
}

<navbar (onClickNav)="popup.show()"></navbar>
<poppy #popup ></poppy>

这篇关于Angular 2中的组件如何通过调用其方法弹出另一个组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆