简体   繁体   English

当父级侦听单击事件时,复选框在 ngTemplateOutlet 内不起作用 - 错误?

[英]Checkbox not working inside ngTemplateOutlet when parent listens for click event - bug?

I've been trying to figure this out for quite a while now.我一直试图弄清楚这一点已经有一段时间了。

Basically, I have a ng-template that contains a single checkbox.基本上,我有一个包含单个复选框的ng-template I then include that into a component by using <ng-container *ngTemplateOutlet> .然后我使用<ng-container *ngTemplateOutlet>将它包含到一个组件中。 The ng-container is contained inside a div that has a click event listener. ng-container包含在具有单击事件侦听器的div中。 The listener does nothing currently, just an empty function.侦听器当前什么都不做,只是一个空函数。

When I run this, everything's good.当我运行它时,一切都很好。 I can check and uncheck the checkbox.我可以选中和取消选中复选框。

Here's the template code:这是模板代码:

<div (click)="handleClick($event)">
  <ng-container *ngTemplateOutlet="foo"></ng-container>
</div>

<ng-template #foo>
  <input type="checkbox">
</ng-template>

If I add a context to the ngTemplateOutlet , though, this mysteriously breaks the checkbox.但是,如果我向ngTemplateOutlet添加context ,这会神秘地破坏复选框。 So, if I update the template code to this:因此,如果我将模板代码更新为:

<div (click)="handleClick($event)">
  <ng-container *ngTemplateOutlet="foo; context: context"></ng-container>
</div>

<ng-template #foo>
  <input type="checkbox">
</ng-template>

and I have a property called context in my component class (just an empty object for now), the checkbox no longer gets checked when I click on it.并且我的组件类中有一个名为context的属性(现在只是一个空对象),单击复选框时不再选中该复选框。

It would probably be easier just to link to the simple example:链接到简单的例子可能会更容易:

https://plnkr.co/edit/LHxdP3XBifuYbgmo3ptm https://plnkr.co/edit/LHxdP3XBifuYbgmo3ptm

It's definitely the context that is causing this issue.这绝对是导致此问题的context When I remove the context , the checkbox works again.当我删除context ,复选框再次起作用。

EDIT: I forgot to mention - if I remove the (click) listener from the containing div , the checkbox works correctly as well.编辑:我忘了提到 - 如果我从包含的div删除(click)侦听器,复选框也可以正常工作。 Could providing a context affect the propagation of events somehow?提供context会以某种方式影响事件的传播?

Could this be an Angular bug?这可能是一个 Angular 错误吗? Or is there some concept I'm missing?还是我缺少一些概念?

Thanks!谢谢!

Remove the get accessor, like trackBy for *ngFor, context should be:删除 get 访问器,例如 *ngFor 的 trackBy,上下文应该是:

context() {
    return {};
}

DEMO演示

or declare context as a property:或将上下文声明为属性:

context = {}

DEMO演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM