angular - Cannot bind Input property to directive
问题描述
I want to dynamically disable click events from a certain DOM. I figured a directive should do the trick. Apparently it is not possible to add / remove directives dynamically, so I just added the conditional parameter:
import { Directive, HostListener, Input } from '@angular/core';
@Directive({
selector: '[disableClickEvent]',
})
export class DisableClickEventDirective {
@HostListener('click', ['$event'])
// workaround as directives can not (yet) be added dynamically
@Input()
disableClickEvent: boolean;
public onClick(event: any): void {
if (this.disableClickEvent) {
event.stopPropagation();
}
}
}
and my html:
<div class="modal-body">
<ng-container class="content" *ngIf="exportTypeSelectionModel$ | async; let exportTypeSelectionModel">
<ul>
<li
[disableClickEvent]="!exportTypeSelectionModel.Condition"
[class.disabled]="!exportTypeSelectionModel.Condition"
>
<span>Some list item</span>
</li>
</ul>
</ng-container>
</div>
I always end up with this when clicking on the li
ng:///SharedModule/MyComponent.ngfactory.js:10 ERROR TypeError: jit_nodeValue_3(...).disableClickEvent is not a function
at Object.eval [as handleEvent] (ng:///SharedModule/MyComponent.ngfactory.js:15)
at handleEvent (:4200/vendor.js:98419)
at callWithDebugContext (:4200/vendor.js:100038)
at Object.debugHandleEvent [as handleEvent] (:4200/vendor.js:99673)
at dispatchEvent (:4200/vendor.js:85506)
at :4200/vendor.js:97351
at HTMLLIElement.<anonymous> (:4200/vendor.js:117167)
at ZoneDelegate.invokeTask (:4200/polyfills.js:3722)
at Object.onInvokeTask (:4200/vendor.js:94422)
解决方案
First you need to attach your directive to 'li'. Like:
<li eveDisableClickEvent [disableClickEvent]="!exportTypeSelectionModel.Condition" ... >
. Then in directive file you should move your function under the host listener decorator. Like: `
@HostListener('click', ['$event'])
onClick(event: any): void {
if (this.disableClickEvent) {
event.stopPropagation();
}
}
` That should help. But it would be better to have some stackblitz with use-case. P.s the thing is that @HostListener needs handler function but in your case compiler goes down and encounter first "disableClickEvent" property which is boolean, so it throws the error that "disableClickEvent is not a function"
推荐阅读
- javascript - 如何从登录的 Google 登录(仅限客户端应用程序)中正确获取访问令牌?
- javascript - 按重量对列表进行排序,选取项目的开头并为其分配自定义重量
- android - 从开始日期到结束日期重复本地通知,一天也重复 1-4 次 Android
- sql - 为什么jsp在同一个表单中多次显示同一个数据?
- php - ajax url路径未定义,如何获取ajax url中的wordpress文件路径?
- pam - 如何使用 pam_exec 和 PAM_TYPE 创建条件行为?
- uwp - UWP TreeView DragEnter 和 DragOver 事件不执行
- scrapy - Scrapy 不会抓取整个网站
- ruby - 在 Sinatra 中,如何渲染 json?
- c# - 如何使用 C# 中文本框的值查询 mySql 表?