2016-06-30 90 views
2

我似乎無法弄清楚數據綁定如何與Angular2中的自定義指令一起工作。比方說,我有一個接受@Input是一個Observable自定義指令FoobarDirective將自定義指令綁定到Angular2中的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

回答

3

我覺得現在的問題是你指令的選擇:

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

由於您使用了錯誤的選擇,該指令不應用這樣Angular2不知道該輸入...

相關問題