5 javascript angular-directive angular
我知道围绕这个问题有无数的问题,我尝试了所有解决方案,但没有一个适合我的需要。尝试过指令,直接在我的组件中尝试过,但它一次都不起作用。
所以我的情况是这样的;我有一个表格视图,在每个表格视图的末尾,您可以通过单击图标打开一个小下拉列表。弹出的下拉菜单是一个小组件。所以在我的父组件中它看起来像这样;
<tbody>
<tr *ngFor="let rows of subscriptionTable.data; let i = index;">
<td *ngFor="let cell of subscriptionTable.data[i].data">
<!-- Table actions -->
<div *ngIf="cell.actions && cell.actions.length > 0">
<app-dropdown
[actions] = cell.actions
(onActionClicked) = "handleSubscriptionAction($event, i)"
>
</app-dropdown>
</div>
</td>
</tr>
</tbody>
Run Code Online (Sandbox Code Playgroud)
所以我正在渲染多个子应用程序下拉组件,如下所示;
<div class="fs-action">
<div class="fs-action__dots" (click)="openActionSheet($event)">
<span class="fs-action__dot"></span>
<span class="fs-action__dot"></span>
<span class="fs-action__dot"></span>
</div>
<ul class="fs-action__list">
<li
class="fs-action__item"
*ngFor="let action of actions; let i = index;"
(click)="actionClicked( $event, i )"
[ngClass]="{'fs-action__item--danger': action.type === 'destructive' }"
>
{{ action.label }}
</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
我现在想做的是,一旦我单击 fs-action 元素外部,下拉列表就会消失。我想在app-dropdown组件内部执行此操作,然后与该组件相关的所有内容都位于同一位置。
但是一旦我附加了指令或其他任何内容,hostlistener就会为每一行添加 get 。每次外部点击都会被多次触发。检查我是否在操作元素之外单击会成为一种负担,因为它会为所有其他元素呈现 false hostlisteners,而为活动元素呈现 true。
这个问题在 stackblitz 中得到了说明;https://stackblitz.com/edit/angular-xjdmg4
我评论了导致内部问题的部分dropdown.component.ts;
public onClickOutside( event ) {
// It executes 3 times, for each of the items that is added
// Even when clicking inside the dropdown, it calls this function
console.log("click")
}
Run Code Online (Sandbox Code Playgroud)
小智 1
我在类似的情况下使用了指令。安装:
npm install --save ng-click-outside
Run Code Online (Sandbox Code Playgroud)
然后导入到你的模块中
import { ClickOutsideModule } from 'ng-click-outside';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, ClickOutsideModule],
bootstrap: [AppComponent]
})
class AppModule {}
Run Code Online (Sandbox Code Playgroud)
在你的组件中
@Component({
selector: 'app',
template: `
<div (clickOutside)="onClickedOutside($event)">Click outside this</div>
`
})
export class AppComponent {
onClickedOutside(e: Event) {
console.log('Clicked outside:', e);
}
}
Run Code Online (Sandbox Code Playgroud)
它有一些选项。您可以在https://www.npmjs.com/package/ng-click-outside中看到它
问候
| 归档时间: |
|
| 查看次数: |
9498 次 |
| 最近记录: |