我从带有复选框输入的数组中选择了一些值,如本例所示
Visit 'http://plnkr.co/edit/N9NXBYcwhon6ITr8RP5y?p=preview'
但我想使用输入装饰器将检查的数组数据传递给另一个组件。如何使已检查的数据成为可观察的并获取新组件中的值,如果我推送或删除一个值,则必须在我的子组件中对其进行编辑
希望你能帮我
创建一个子组件,如下所示@Input
being Observable<Array<string>>
@Component({
selector: 'another-component',
template: `
{{checkBoxValues | json}}
`
})
export class AnotherComponent implements OnChanges, OnInit{
@Input() selectedArray:Rx.Observable.of(Array<string>);
checkBoxValues:any[] = [];
ngOnInit(){
}
ngOnChanges(){
if(this.selectedArray){
this.selectedArray.subscribe(data=>{
if(data!= undefined){
console.log('subscribedData',data);
this.checkBoxValues=data;
}
})
}
}
}
您的父组件应修改如下,
@Component({
selector: 'my-app',
template: `
<ul>
<li *ngFor="let option of options">
<input type="checkbox" [attr.name]="options" [value]="option" (change)="updateChecked(option, $event)">{{option}}
</li>
</ul>
<span *ngIf="checked">
<another-component [selectedArray]="selectedArray"> </another-component>
</span>
`,
})
export class App {
options = ['a', 'b', 'c', 'd', 'e'];
checked: string[] = [];
selectedArray:Observable<Array<string>>;
constructor(){
}
updateChecked(option, event) {
console.log('event.target.value ' + event.target.value);
var index = this.checked.indexOf(option);
if(event.target.checked) {
console.log('add');
if(index === -1) {
this.checked.push(option);
}
} else {
console.log('remove');
if(index !== -1) {
this.checked.splice(index, 1);
}
}
this.selectedArray=Rx.Observable.from([this.checked]);
}
}
现场演示 http://plnkr.co/edit/P5q9ju5gp7Y8FipkXgRH
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)