2016-06-30 8 views
2

Angular2のカスタムディレクティブでデータバインディングがどのように機能するかわかりません。Angular2でObservableにカスタムディレクティブをバインドする

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

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

そして、このように実装するコンポーネント::のは、私はObservableある@Inputを受け入れるカスタムディレクティブFoobarDirectiveを持っているとしましょう

@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があります。

答えて

3

私は問題があなたのディレクティブのセレクタであることを考える:

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

あなたは間違った選択を使用しているのでAngular2この入力について知らないので、ディレクティブが適用されていません...

関連する問題