【问题标题】:Binding custom directive to Observable in Angular2在Angular2中将自定义指令绑定到Observable
【发布时间】:2016-11-02 21:16:25
【问题描述】:

我似乎无法弄清楚数据绑定如何与 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

【问题讨论】:

    标签: typescript angular rxjs angular2-directives


    【解决方案1】:

    我认为问题在于您的指令的选择器:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-19
      • 2012-12-14
      • 2019-05-30
      • 1970-01-01
      • 2016-07-16
      • 1970-01-01
      • 2017-01-28
      • 2017-07-09
      相关资源
      最近更新 更多