如何在自定义组件的宿主元素上使用自定义指令



我有一个自定义指令,该指令应收听自定义组件的ngModelChange并在数组中添加或删除项目。

这是指令:

@Directive({
  selector: '[selectedItems]'
})
export class SelectedItemsDirective {
  @Input('ngModel') ngModel: boolean;
  @Input() mainNgModel: boolean;
  @Input() items: any[] = [];
  @Input() item: any;
  @Input() itemKey: string;
  @Output() itemsChange: EventEmitter<any> = new EventEmitter<any>();
  @HostListener('ngModelChange')
  modelChange() {
    const i: number = this.items.indexOf(this.item[this.itemKey]);
    if (i === -1 && this.ngModel) {
      this.items.push();
    }
    else {
      this.items.splice(i, 1);
    }
    this.itemsChange.emit(this.items);
  }
}

然后将其使用:

<checkbox [(ngModel)]="event.isChecked" [(selectedItems)]="selectedEvents" [items]="events" [item]="event"></checkbox>

但这是不起作用的,因为:

Can't bind to 'selectedItems' since it isn't a known property of 'checkbox'.

,我猜测该指令的输入属性也会发生同样的情况。

我似乎无法搜索我的解决方案,该解决方案与我要实现的目标非常接近。我已经在SharedModule中声明并导出了该指令,然后将其导入到复选框的模块中。

为此,我还需要做什么才能工作?

我相信您忘了将directives应用于@Component()

示例:

@Component({
    selector: 'YourApp',
    templateUrl: 'YourTemplateUrlHere',
    directives: [SelectedItemsDirective] 
})

还有一个建议不要编写所有代码,只需绑定指令,然后添加非常基本的console.log()东西,然后一次添加所有这两种绑定。

花了三个小时的调试只是为指令中的拼写错误。是的体验:(

最新更新