Home > Enterprise >  Angular directive only binds to an element when it is nested within an *ngIf directive
Angular directive only binds to an element when it is nested within an *ngIf directive

Time:12-01

So I have this very odd issue. I have a directive declared within a module that a component is also registered. The page does not compile, saying:

Can't bind to 'entityEditPanel' since it isn't a known property of 'button'. However, if I put *ngIf="true" in the container above the button, the page compiles.

I've tried moving and altering the directive and the component, but it is consistent throughout the module. No other directives do this.

Here is the directive:

@Directive( {
    selector: '[entityEditPanel]',
} )
export class EntityEditPanelDirective {
...
}

Here is the component:

@Component( {
    selector: 'work-item-form',
    templateUrl: './workItemForm.component.html'
} )
export class WorkItemFormComponent extends EntityFormComponent<IWorkItemModel> {
...
}

Here is the module:

@NgModule( {
    declarations: [
        // Directives
        EntityEditPanelDirective,
        // Production
        WorkItemFormComponent
        ...
    ],
    exports: [
        // Directives
        EntityEditPanelDirective,
        // Production
        WorkItemFormComponent
        ...
    ]
}
export class AdminModule {
}

This is the template page for WorkItemForm. This doesn't compile:

<span >
    <button type="button" 
            [entityEditPanel]
            [entity]="entity">
        <i ></i>
    </button>
</span>

This does compile:

<span  *ngIf="true">
    <button type="button" 
            [entityEditPanel]
            [entity]="entity">
        <i ></i>
    </button>
</span>

CodePudding user response:

To use directive you don't need [] try to change your html to

 <button type="button" 
            entityEditPanel
            [entity]="entity">
        <i ></i>
    </button>

You would use brackets when you have input parameter on component or Directive [entity]="entity"

So lets say if you have

@Directive( {
    selector: '[entityEditPanel]',
} )
export class EntityEditPanelDirective {
   @Input() entityEditPanel: string;
}

Then you would use it

 <button type="button" 
            [entityEditPanel]="'red'"
            [entity]="entity">
        <i ></i>
    </button>
  • Related