[英]Angular structural directive with CSS selector
I am creating a custom dropdown menu.我正在创建一个自定义下拉菜单。 The menu contains some items and should remain open when a user clicks on any of these items.
菜单包含一些项目,当用户单击这些项目中的任何一个时,它应该保持打开状态。 To check if the user clicks inside the dropdown menu I check via
window.onclick
if event.target.matches('dropdown-content *')
.要检查用户是否在下拉菜单中单击,我通过
window.onclick
if event.target.matches('dropdown-content *')
检查。 See the snippet below for context.有关上下文,请参见下面的片段。
<div id="myDropdown" class="dropdown-content">
<div class="dropdown-grid">
<div class="add-offset">
<div class="dd-header">
<div (click)="setupNewCol()"><i class="fas fa-plus plus-sign"></i></div>
</div>
</div>
</div>
</div>
This works, but when I add *ngIf
to the div with the function call the CSS selector 'dropdown-content *'
doesn't seem to work anymore.这可行,但是当我使用 function 将
*ngIf
添加到 div 时,调用 CSS 选择器'dropdown-content *'
似乎不再起作用。 This is the HTML with the *ngIf
这是带有
*ngIf
<div id="myDropdown" class="dropdown-content">
<div class="dropdown-grid">
<div class="add-offset">
<div class="dd-header">
<div *ngIf="!settingNewOffset; else offsetSelection" (click)="setupNewCol()"><i class="fas fa-plus plus-sign"></i></div>
<ng-template #offsetSelection>
<div (click)="addCol()">
CLICK ME
</div>
</ng-template>
</div>
</div>
</div>
</div>
With the introduction of the *ngIf
in combination with ng-template
the CSS selector doesn't recognize the clicks to be part of '.dropdown-content *'
anymore.随着
*ngIf
与ng-template
结合的引入,CSS 选择器不再将点击识别为'.dropdown-content *'
一部分。 Why is this and what is a solution to this problem?为什么会这样,这个问题的解决方案是什么?
Why it won't register the click on target 'dropdown-content' is probably because now the clicked target is a div, that does not have 'dropdown-content'.为什么它不会注册对目标“下拉内容”的点击可能是因为现在点击的目标是一个 div,没有“下拉内容”。 Probably the target parent has that class, but not the target.
可能目标父母有那个 class,但没有目标。
To check if a user clicks on any of the items.检查用户是否点击了任何项目。 You already have methods
addCol()
or setupNewCol()
.您已经有方法
addCol()
或setupNewCol()
。 If this method runs then user has clicked some of the item where the method was attached.如果此方法运行,则用户单击了附加该方法的某些项目。 You could also just attach another method to the item eg
(click)="addCol(); onItemClick($event)"
您也可以将另一种方法附加到项目,例如
(click)="addCol(); onItemClick($event)"
onItemClick(event:any) {
console.log(event)
}
(click)="addCol(); event.stopPropagation()"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.