我从数组中选择了一些带有复选框输入的值,例如
访问'http://plnkr.co/edit/N9NXBYcwhon6ITr8RP5y?p=preview'
但是我希望使用输入装饰器将已检查的数组数据传递给另一个组件。如果我推送或删除必须在我的子组件中编辑的值,如何将de checked数据设为可观察数据并获取新组件中的值
希望你能帮助我答案 0 :(得分:1)
如下所示创建子组件,@Input
为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]);
}
}