我练习角度的视图和模板。 我想创建一个像角度材料数据表但从零开始的表;
我有这样的模板:
...
<app-table
[dataSource]="data"
>
<ng-container appTableColumn="created">
<th *appTableHeader>Created</th>
<td appTableCell *appTableData="let element">{{element.created}}</td>
</ng-container>
<ng-container appTableColumn="name">
<th *appTableHeader>Name</th>
<td appTableCell *appTableData="let element">{{element.name}}</td>
</ng-container>
<ng-container appTableColumn="type">
<th *appTableHeader>Type</th>
<td appTableCell *appTableData="let element">{{element.type}}</td>
</ng-container>
<tr appTableRow *appTableRowDef="let row; columns: displayColumns"></tr>
</app-table>
...
我生成了包含ngForOf实现副本的行。我使用@ContentChildren来访问行的已创建组件。所以我在ngAfterContentInit()中订阅了它的更改。
...
@ContentChildren(TableRowComponent, {descendants: true}) rows:QueryList<TableRowComponent>;
...
ngAfterContentInit(){
this.__rowsSubscription = this.rows.changes.subscribe(() => {
this.rows.forEach((row:TableRowComponent, index) => {
row.row = this.dataSource[index];
row.rowIndex = index;
row.columns = this._getRowCellsOutlet(row.row);
...
...
在TableRowComponent中,我想做同样的事情,但我不能。我的计划是当它的列数组发生变化时,我用ngDoCheck和iterableDiffer检测它,然后我只是在视图上应用了更改。 (这部分工作我通过单元格模板[appTableData指令]生成了视图)。所以在此之后我想访问单元组件,就像我之前使用行一样,但@ContentChildren不起作用! :(
行代码:
...
export class TableRowComponent implements OnInit, AfterContentInit, OnDestroy, DoCheck {
row:Object;
rowIndex:number;
columns:CellOutlet[];
iterableDiffer:IterableDiffer<{}> = this._iterableDiffers.find([]).create(null);
@ViewChild(RowOutletDirective) rowOutlet:RowOutletDirective;
@ContentChildren(TableCellComponent, {descendants: true}) cells: QueryList<TableCellComponent>;
__cellsSubscription:Subscription = null;
identifier:string = `table-row-${identifier++}`;
constructor(
public _vcr: ViewContainerRef,
private _iterableDiffers: IterableDiffers
){}
ngOnInit(){
}
ngAfterContentInit(){
//console.log(this.cells); //shows empty QueryList
this.__cellsSubscription = this.cells.changes.subscribe(() => {
console.log(this.cells); //does not run (here is no changes but I generate cells at _applyChanges)
});
}
ngDoCheck(){
if(this.iterableDiffer){
const changes = this.iterableDiffer.diff(this.columns);
if(changes){
this._applyChanges(changes);
}
}
}
ngOnDestroy(){
if(this.__cellsSubscription){
this.__cellsSubscription.unsubscribe();
}
}
private _applyChanges(changes: IterableChanges<{}>){
changes.forEachOperation(
(item: IterableChangeRecord<any>, adjustedPreviousIndex: number, currentIndex: number) => {
if (item.previousIndex == null) {
const view = this.rowOutlet._vcr.createEmbeddedView(
item.item.cell._tpl, {$implicit: item.item.data}
);
} else if (currentIndex == null) {
this.rowOutlet._vcr.remove(adjustedPreviousIndex);
} else {
const view = this.rowOutlet._vcr.get(adjustedPreviousIndex) !;
this.rowOutlet._vcr.move(view, currentIndex);
}
});
}
}
...
当我生成单元格时,我不知道为什么QueryList为空,为什么在视图中生成某些内容时没有更改订阅者:|