将自定义指令绑定到Angular2

时间:2016-06-30 16:33:06

标签: typescript angular rxjs angular2-directives

我似乎无法弄清楚数据绑定如何与Angular2中的自定义指令一起使用。我们假设我有一个自定义指令FoobarDirective,它接受​​@Input Observable

@Directive({
  selector: 'foobar'
})
export class FoobarDirective implements OnInit {
  @Input() anObservable: Observable<string[]>;

  ngOnInit() {
    this.anObservable.subscribe(values => {
      console.log(values);
    });
  }
}

这样的实施组件:

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>{{ message }}</h2>
      <div foobar [anObservable]="toBind"></div>
    </div>
  `,
  directives: [FoobarDirective]
})
export class App implements OnInit {
  message: string;
  toBind: Subject<string[]>;

  ngOnInit() {
     this.message = 'Angular2 works!';

     this.toBind = new Subject<string[]>();
     this.toBind.next(['a', 'b', 'c']);
  }
}

...但我收到以下错误: Can't bind to 'anObservable' since it isn't a known native property

这里是plunker

1 个答案:

答案 0 :(得分:3)

我认为问题是指令的选择器:

@Directive({
  selector: '[foobar]' // <------
})
export class FoobarDirective implements OnInit {
  (...)
}

由于您使用了错误的选择器,因此未应用该指令,因此Angular2不知道此输入......

相关问题