嵌套NgIf和(点击)Angular2 [英] Nesting NgIf and (click) in Angular2

查看:99
本文介绍了嵌套NgIf和(点击)Angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,点击后会产生许多子元素,我想创建一个如果用户点击除子按钮之外的任何地方以外的任何地方都会崩溃的效果。为此,我想在整个页面上附加一个(点击)= xyz(),但只有在按钮被展开后才有效。然后,我将定位页宽选择器的子元素(用css z-index)。是否有可能实现这一点,或者有更好的方式来做到这一点?



这是我迄今为止(只从按钮点击切换)。

p>

您仍然可以使用声明式方法,并在折叠时忽略事件。

  @HostListener('window:click',['$ event '])
windowClickHandler(event){
if(!this.expanded)return;
collapse();
}

另一种方式可以是只在展开时启用的指令

  @Directive({
选择器:'globalClick'
主机:{
'[style.display] ':''none'',
}
}
class GlobalClick {
@Output()globalClick:EventEmitter = new EventEmitter();

@HostListener('window:click',['$ event'])
windowClickHandler(event){
this.globalClick.emit(event);
}
}

然后像使用它一样

 < span * ngIf =expanded(globalClick)=collapse($ event)> 


I have got a button which when clicked produces a number of child elements, I want to create a "collapse if the user clicks anywhere other than one of the child buttons" effect. To do this, I want to attach a (click) = xyz() to the whole page, but only have that active if the button has been expanded. Then I would position the child elements infront of the page wide selector (with css z-index). Is it possible to achieve that, or is there a better way of doing that?

Here is what I have so far (only toggles from the button click).

解决方案

You can still use the declarative approach and just ignore events while collapsed

@HostListener('window:click', ['$event'])
windowClickHandler(event) {
  if(!this.expanded) return;
  collapse();
}

another way could be a directive that is only enabled when expanded

@Directive({
  selector: 'globalClick'
  host: {
      '[style.display]':'"none"',
  }
}
class GlobalClick {
  @Output() globalClick:EventEmitter = new EventEmitter();

  @HostListener('window:click', ['$event'])
  windowClickHandler(event) {
    this.globalClick.emit(event);
  }
}

and then use it like

<span *ngIf="expanded" (globalClick)="collapse($event)">

这篇关于嵌套NgIf和(点击)Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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