【发布时间】:2021-02-22 13:11:42
【问题描述】:
在我的 Angular 10 应用程序中,我正在通过组件工厂解析器加载一个包含 AG Grid 的组件。
当我通过按钮触发工厂解析器时,一切正常。显示 Grid 并正确触发 gridReady 事件。
但是,如果我通过ngOnInit()或ngAfterViewInit()等触发组件工厂解析器,则不会触发gridReady事件并且不会显示网格。
我尝试使用 ChangeDetectorRef 服务来强制进行更改检测,但这并没有改变任何东西。
这是组件工厂解析器的代码:
export class PlannerComponent implements OnInit {
@ViewChild('ordersContainer', {read: ViewContainerRef}) container: ViewContainerRef;
public orders = [];
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private httpClient: HttpClient
) { }
ngOnInit(): void {
this.loadOpenOrders();
}
loadOpenOrders() {
this.httpClient.get('/orders')
.pipe(map((result: any) => {
const orders = result._embedded.orders;
orders.forEach((function (order) {
this.addOrder();
}).bind(this))
}))
.subscribe()
}
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.gridApi.sizeColumnsToFit();
}
addOrder() {
// Create component dynamically inside the ng-template
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(OrderComponent);
const newOrder = this.container.createComponent(componentFactory);
// Push the component so that we can keep track of which components are created
this.orders.push(newOrder);
}
}
在视图中,组件是这样加载的:
<div class="container">
<div class="row">
<div class="col-6">
<div class="card card-custom gutter-b">
<ag-grid-angular
style="width: 100%; height: 600px;"
class="ag-theme-alpine"
[rowData]="ordersToPlan"
[columnDefs]="columnDefs"
[rowSelection]="rowSelectionType"
(gridReady)="onGridReady($event)" <==== Only triggered through button click, but not on ngOnInit()
[animateRows]="true"
>
</ag-grid-angular>
</div>
</div>
<div class="col-6">
<button class="btn btn-success mb-5" (click)="addOrder()">Add a new Order</button>
<div>
<ng-template #ordersContainer>
</ng-template>
</div>
</div>
</div>
</div>
任何帮助表示赞赏:-)
【问题讨论】: