首页 > 解决方案 > 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)

标签: angularangular-directive

解决方案


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"


推荐阅读