【问题标题】:Observable of @Input property@Input 属性的 Observable
【发布时间】:2017-11-12 00:50:21
【问题描述】:

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

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

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

希望你能帮助我

【问题讨论】:

  • 我认为我没有按照您的要求进行操作,您能否澄清一下您想要的行为是什么?
  • @LLaza 在下面查看我的答案。
  • 也请为我的回答点赞
  • 我的回答有帮助吗??

标签: angular


【解决方案1】:

如下创建一个子组件,@InputObservable<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]);
  }
}

LIVE DEMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2013-09-09
    • 1970-01-01
    • 2017-11-07
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多