我试图动态地将选择下拉组件注入网格colomn evrytime我创建了一个新行。实际上,下拉组件总是被注入同一行。
我的目标是每次创建新行时从可用列表中删除所选值
我的父母组件:
export class ReferenceTableComponent implements AfterViewInit {
observable: Observable<any>;
@ViewChild('selectorTarget', {read: ViewContainerRef}) selectorTarget;
// colors
@Input() public datas: Array<string>;
public availableColors: Array<string>;
@Input() public styleId: string;
@Input() public headList: Array<string>;
public rows: Array<any> = [{}];
public rowIDs: Array<any> = [];
constructor(private _cr: ComponentFactoryResolver) {
}
ngAfterViewInit() {
this.computeAvailableColors();
}
addRow() {
this.rows.push({});
const select: ComponentRef<SelectOptionsComponent> =
this.selectorTarget.createComponent(
this._cr.resolveComponentFactory(SelectOptionsComponent)
);
select.instance.availableColors = this.availableColors;
select.instance.color = this.rows[0].color;
select.instance.changed.subscribe(evt => {
this.availableColors = this.availableColors.filter(c => c !== evt.color);
});
}
computeAvailableColors() {
this.availableColors = _.concat([''], this.datas);
this.rowIDs = _.map(this.rows, 'color')
this.availableColors = _.difference(this.availableColors, this.rowIDs);
const select: ComponentRef<SelectOptionsComponent> =
this.selectorTarget.createComponent(
this._cr.resolveComponentFactory(SelectOptionsComponent)
);
select.instance.availableColors = this.availableColors;
select.instance.color = this.rows[0].color;
select.instance.changed.subscribe(evt => {
this.availableColors = this.availableColors.filter(c => c !==
evt.color);
});
}
}
父html:
<tbody>
<tr *ngFor="let row of rows">
<td></td>
<td>
<div #selectorTarget></div>
</td>
<td *ngFor="let headItem of headList"><input class="input"
type='text' #qty/></td>
</tr>
</tbody>
关于孩子的组件,我有:
@Component({
selector: 'kia-select-options',
template: `<div><select [(ngModel)]="color"
(ngModelChange)="sendColorEvent($event)">
// value is a string or number
<option *ngFor="let obj of availableColors">{{obj}}</option>
</select></div>`
})
export class SelectOptionsComponent {
// couleurs
@Input() public availableColors: Array<string>;
@Input() public color: string;
@Output()
public changed = new EventEmitter();
constructor(private injector: Injector) {
}
sendColorEvent(color) {
console.log(event)
this.changed.emit({ color: color });
}
}
答案 0 :(得分:0)
我通过在子组件中注入所有表块而不仅仅是选择器div
来解决了这个问题所以现在在我的儿童模板中:
<table class="table table-hover table-striped table-condensed table-scroll default-cursor">
<tbody>
<tr>
<td></td>
<td>
<select [(ngModel)]="color" (ngModelChange)="sendColorEvent($event)">
<option *ngFor="let obj of availableColors">{{obj}}</option>
</select>
</td>
<td *ngFor="let headItem of headList"><input class="input" type='text' #qty/></td>
</tr>
</tbody>
</table>