可观察到@Input属性 [英] Observable of @Input property

查看:87
本文介绍了可观察到@Input属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数组中选择了一些带有复选框输入的值,例如本例

I have some selected values from array with checkbox inputs like this example

访问'http://plnkr.co/edit/N9NXBYcwhon6ITr8RP5y?p=preview'

但是我想使用输入装饰器将检查的数组数据传递给另一个组件.如何在我的新组件中使已检查的数据成为可观察的并获取值,如果我推入或删除一个值,则必须在其子组件中对其进行编辑

but I want to pass the checked array data to another component, with an input decorator. How can I make de checked data an observable an get the value in my new component, if I push or remove a value it has to be edited in my child component

希望你能帮助我

推荐答案

按如下所示创建子组件,其中@InputObservable<Array<string>>

Create a child component as below, with @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;
       }
     })
   }
 }
}

您的父组件应进行如下修改,

Your parent component should be modified as below,

@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]);
  }
}

实时演示

LIVE DEMO

这篇关于可观察到@Input属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆