Angular structural directive with CSS selector

152 Views Asked by At

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 *'). 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. This is the HTML with the *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. Why is this and what is a solution to this problem?

1

There are 1 best solutions below

0
On
  1. 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'. Probably the target parent has that class, but not the target.

  2. To check if a user clicks on any of the items. You already have methods addCol() or 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 e.g (click)="addCol(); onItemClick($event)"

onItemClick(event:any) {
console.log(event)
}
  1. I don't see where the menu closing part is but using onItemClick you could just cancel that or try to cancel the event from propagating at all.

(click)="addCol(); event.stopPropagation()"