【发布时间】:2019-10-01 16:09:31
【问题描述】:
我有一个由id: number(Gist for the Data as JSON) 标识的复选框列表。如果我选中第一个复选框,则 id 值将存储到 Set 中。
我的ParentComponent如下:
parent.component.ts代码sn-p
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 }}
但每当我选中复选框时,它只会在浏览器中为我提供{},并且根据changeCheck selections 应该在Set 中添加值
如果我使用{{selected}},它会一直为我提供[object Set]。如何将 Set 从父组件传递给子组件?
在子组件中使用OnChange 指令后,我执行以下操作:
ngOnChanges(change: SimpleChange) {
console.log(change.currentValue);
}
这为我提供了 Set(),但 selected 在浏览器控制台中仍然是一个空集。
【问题讨论】:
标签: angular set angular-directive