将集合传递给Angular中的子组件

时间:2019-05-14 15:13:25

标签: angular set angular-directive

我有一个由id: numberGist for the Data as JSON)标识的复选框列表。如果选中第一个复选框,则id值将存储到Set中。

我的 ParentComponent 如下:

parent.component.ts代码段

import { Component, OnInit } from '@angular/core';
import * as FilterFunc from 'src/assets/FilterFunction.json';

const Filters: any = FilterFunc;

@Component({
  selector: 'parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  filters = Filters.default;
  selections = new Set();

  constructor() {
  }
  ngOnInit(): void {
  }
  changeCheck(id: number, event: any) {
    (event.target.checked) ?
      this.selections.add(id):
      this.selections.delete(id);

  }
}

parent.component.html代码段:

<!--- ....>
<div *ngFor="let label of filter['labels']">
          <div class="form-check">
            <input class="form-check-input"
                   type="checkbox"
                   value="{{label['id']}}"
                   id="{{label['id']}}"
                   [(ngModel)]="label['checked']"
                   (change)="changeCheck(label['id'], $event)"
            >
              <label class="form-check-label" for="{{label['id']}}">
                {{label['name']}}
              </label>
          </div>
      </div>

我希望将此selections: Set传递给子组件,并在“父”的HTML组件中添加以下内容:

<child [selected]=selections></child>

子组件中:

child.component.ts

import { Component, OnInit, Input} from '@angular/core';
@Component({
  selector: 'child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
  providers: [
    // service that I need
  ]
})
export class ChildComponent implements OnInit {


  @Input()selected: any; // not sure if `Set` is a type for a variable in TS

  constructor(private service: ExploreService) { }

  ngOnInit() {      }

   someFunct() {
      // Use the incoming `selected` here.
   }

}

child.component.html

   {{ selected | json }}

但是,每当我选中一个复选框时,它仅在浏览器中为我提供{},并且根据changeCheckselections应该在Set

如果我使用{{selected}},它将继续为我提供[object Set]。如何将Set从父组件传递给子组件?

在子组件中使用OnChange指令后,我将执行以下操作:

ngOnChanges(change: SimpleChange) {
console.log(change.currentValue);
}

这为我提供了Set(),但是selected在浏览器的控制台中仍然是空集。

1 个答案:

答案 0 :(得分:0)

发送给孩子的唯一可能方法是将Set转换为数组,然后将其传递给孩子组件

我必须创建一个私有成员Set,并将其转换为Array

private _selections = new Set();
selections: number[] = [];

在检查事件结束后在changeCheck(id: number, event: any)函数内

(event.target.checked) ? this._selection.add(id) : this._selection.delete(id);
this.selections = Array.from(this._selections);

最后,当父母每次传递ID值时,它将与OnChanges钩一起使用。