Angular 创建动态组件断言错误

问题描述 投票:0回答:1

我遇到一种情况,我需要动态创建要在 Angular/PrimeNG 选项卡中显示的组件。

应用程序启动时未定义选项卡。选项卡的内容取决于为用户定义的权限,因此必须动态创建。某些选项卡可能具有相同的布局,但填充了不同的数据(例如选项卡 1 包含来自美国的预订数据,选项卡 2 包含来自英国的预订数据等,选项卡 3 包含美国的付款数据,选项卡 4 包含英国的付款数据)

所以我想动态地创建一切。用户登录后,我提取他的权限并根据它创建所有选项卡作为动态组件。这可行,但我在 Chrome 中遇到了一个丑陋的错误。

我的观点是这样的:

<p-tableView orientation="left">
  <p-tabPanel *ngFor="let tab of tabs" [header]="tab.title">
    <ng-container *ngComponentOutlet="tab.contentComponent"></ng-container
  </p-tabPanel>
</p-tableView>

现在是代码:

tabs { title: String, contentComponent: any}[] = [];

constructor(..., private viewContainerRef : ViewContainerRef, private injector: EnvironmentInjector) { }

ngOnInit() {
   const bookedRange = this.viewContainerRef.createComponent(BookedRangeComponent, {environmentInjector: this.injector});
    // Setting some Parameter
   bookedRange.instance.filterBookedID = 1000;
   bookedRange.instance.filterUserParam = "AB";
   ...
  this.tabs = [
    { title: "DefaultBookedView", contentComponent: bookedRange }
    ...
  ]

这里是 BookedRangeComponent:

@Component({
selector: 'booked-range',
templateUrl: 'booked-range.html',
})
export class BookedRangeComponent {
   filterBookedID : number;
   filterUserParam: string;
....
}

当我启动此组件时,该组件似乎已正确创建,并且也显示在带有所有参数集的选项卡视图中,但在 Chrome 的开发控制台中我看到以下错误:

ASSERTION ERROR: It looks like Component Factory was provided as the first argument and an options object as the second argument. This combination of arguments is incompatible. You can either change the first argument to provide component type or change the second argument to be a number (representing an index at which to insert the new component's host view into the container

如果我删除最后的选项部分,也会发生同样的情况:

const bookedRange = this.viewContainerRef.createComponent(BookedRangeComponent);

完全相同的错误。

有什么解决办法吗?或者更好的想法?

angular typescript primeng
1个回答
0
投票

您收到的错误不是来自调用

this.viewContainerRef.createComponent(BookedRangeComponent)

但来自

*ngComponentOutlet
内部所做的类似操作。

*ngComponentOutlet

 接受组件类作为输入,并处理创建组件实例并将其添加到 DOM 所需的所有内容,因此您无需使用 
this.viewContainerRef.createComponent(BookedRangeComponent)
 来完成此操作。

© www.soinside.com 2019 - 2024. All rights reserved.