Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度2-单击组件失败_Angular_Angular2 Template - Fatal编程技术网

Angular 角度2-单击组件失败

Angular 角度2-单击组件失败,angular,angular2-template,Angular,Angular2 Template,使用Angular 2,我有一个组件,它有一个小的弹出窗口。关闭单击将关闭弹出窗口(即,单击文档中除弹出窗口外的任何位置将关闭弹出窗口)。我使用HostListener来实现这个效果 当没有内部元素时,这将按预期工作。但是,如果弹出窗口具有内部元素(例如,内部元素),单击弹出窗口将关闭它。这不是期望的行为 此代码按预期工作: @Component({ selector: 'my-app', template: ` <h4 class="example" (click)="s

使用Angular 2,我有一个组件,它有一个小的弹出窗口
。关闭单击将关闭弹出窗口(即,单击文档中除弹出窗口外的任何位置将关闭弹出窗口)。我使用
HostListener
来实现这个效果

当没有内部元素时,这将按预期工作。但是,如果弹出窗口具有内部元素(例如,内部元素),单击弹出窗口将关闭它。这不是期望的行为

此代码按预期工作:

@Component({
  selector: 'my-app',
  template: `
    <h4 class="example" (click)="showPopup = true">
      Click to show popup that works as expected
    </h4>

    <div *ngIf="showPopup" class="example popup">
      Click anywhere besides here to dismiss me
    </div>
  `,
})
export class App {
  public showPopup = false;

  @HostListener('document:click', ['$event']) showThePopup(e: Event) {
    if (!e.target.classList.contains('example')) {
      this.showPopup = false;
    }
  }
}
@组件({
选择器:“我的应用程序”,
模板:`
单击以显示按预期工作的弹出窗口
单击此处以外的任何位置可解雇我
`,
})
导出类应用程序{
public showPopup=false;
@HostListener('document:click',['$event'])显示Popup(e:event){
如果(!e.target.classList.contains('example')){
this.showPopup=false;
}
}
}
但是,以这种方式更改模板将失败:

@Component({
  selector: 'my-app',
  template: ` 
    <h4 class="example" (click)="showPopup = true">
      Click to show popup that work incorrectly
    </h4>

    <div *ngIf="showPopup" class="example popup">
      <p>Clicking here will dismiss me, which should not happen</p>
    </div>
  `,
})
@组件({
选择器:“我的应用程序”,
模板:`
单击以显示工作不正确的弹出窗口
单击此处将解雇我,这是不应该发生的

`, })
什么样的编码方法可以使代码正常工作


工作Plunker:

我建议您将弹出窗口分离到不同的组件中,它不会试图找出单击元素的任何父级是否具有弹出窗口类,这将为您节省很多麻烦

这是一个展示这个概念的作品


解释

当弹出窗口位于其他组件中时,您可以使用访问整个组件的本机元素,然后检查它是否包含单击事件的目标

我们使用
mousedown
,以便它在触发
(单击)
事件之前运行

@HostListener('document:mousedown', ['$event']) showThePopup(e: Event) {
    if(!this._eref.nativeElement.contains(e.target)){
        this.showPopup = false;
    }
}
通过将定义添加到构造函数,可以公开变量
\u eref

constructor(private _eref: ElementRef) { }
在父组件中,您可以利用和
显示弹出窗口:

app.html


单击以显示按预期工作的弹出窗口
这是一个弹出窗口

弹出式html



p
没有
example
类,因此单击它将关闭弹出窗口。如果e.targetOps后缺少括号,请立即修复。谢谢
<h4 class="example" (click)="mypopup.show()">
  Click to show popup that works as expected
</h4>

<popup #mypopup>
  <div class="inside"><p>This is a Popup</p></div>
</popup> 
<div *ngIf="showPopup" class="example popup">
  <ng-content></ng-content>
</div>