Observable property @Input

I have some selected values ​​from a checkbox tabbed array like this example

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

but I want to pass the checked array data to another component using an input decorator. How can I make the checked data observable, get the value in my new component if I click or delete the value it should edit in my child component

hope you help me

0


source to share


1 answer


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

      

Your parent component should be modified as shown 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

+1


source







All Articles