【问题标题】:How to use custom directive on a custom component's host element如何在自定义组件宿主元素上使用自定义指令
【发布时间】:2017-11-30 10:58:00
【问题描述】:

我有一个自定义指令,它应该监听自定义组件的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 中声明并导出了该指令,然后将其导入到复选框的模块中。

我还需要做什么才能使其正常工作?

【问题讨论】:

    标签: angular typescript angular2-directives angular2-components


    【解决方案1】:

    我相信您忘记将directives 应用到您的@Component()

    示例:

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

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

    仅针对指令中的拼写错误花费了三个小时进行调试。耶经验:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 2016-08-24
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多