将自定义指令绑定到 Angular2 中的 Observable
Binding custom directive to Observable in Angular2
我似乎无法弄清楚数据绑定如何与 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。
我认为问题出在你的指令选择器上:
@Directive({
selector: '[foobar]' // <------
})
export class FoobarDirective implements OnInit {
(...)
}
由于您使用了错误的选择器,因此未应用该指令,因此 Angular2 不知道此输入...
我似乎无法弄清楚数据绑定如何与 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。
我认为问题出在你的指令选择器上:
@Directive({
selector: '[foobar]' // <------
})
export class FoobarDirective implements OnInit {
(...)
}
由于您使用了错误的选择器,因此未应用该指令,因此 Angular2 不知道此输入...