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

时间:2017-06-27 11:42:24

标签: angular typescript angular2-directives angular2-components

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

为了使其发挥作用,我还需要做些什么?

1 个答案:

答案 0 :(得分:0)

我相信您忘记将app.directive('toggleRadio', function($timeout) { return { restict: 'A', link: function(scope, el, attrs) { var radioState; el.on('click', function(){ if (radioState === this) { this.checked = false; radioState = null; } else { radioState = this; } scope.$apply(); }); } } 应用于directives

示例:

@Component()

还有一个建议不要编写所有代码,只需先绑定指令然后添加非常基本的@Component({ selector: 'YourApp', templateUrl: 'YourTemplateUrlHere', directives: [SelectedItemsDirective] }) 内容,然后一次添加所有这些双向绑定。

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