gpt4 book ai didi

javascript - 如何在 Angular 12 中动态加载组件

转载 作者:行者123 更新时间:2023-12-05 02:37:52 28 4
gpt4 key购买 nike

我学到的路here在 Angular 文档中,是在容器引用上调用 createComponent()。

我没有像示例中那样使用输入,而是导入一个组件并尝试直接传递它,因为 also in the docs它说:

Angular no longer requires component factories to dynamically create components. Use different signature of the createComponent method, which allows passing Component class directly.

但是为什么我的编译器会提示。根据我对规范的理解,以下是推荐的解决方案。

  loadMore() {
const viewContainerRef = this.resultArea.viewContainerRef;
const componentRef = viewContainerRef.createComponent<RecentGridComponent>(RecentGridComponent);
}

但是我明白了

Argument of type 'typeof RecentGridComponent' is not assignable to parameter of type 'ComponentFactory'.Type 'typeof RecentGridComponent' is missing the following properties from type 'ComponentFactory': selector, componentType, ngContentSelectors, inputs, and 2 more.ts(2345)

相反,我必须实例化一个工厂(完整代码)

import { Component, ComponentFactoryResolver, OnInit, ViewChild } from '@angular/core';
import { RecentGridComponent } from '../recent-grid/recent-grid.component';
import { ResultAreaDirective } from '../result-area.directive';

@Component({
selector: 'app-search-filters',
templateUrl: './search-filters.component.html',
styleUrls: ['./search-filters.component.sass']
})
export class SearchFiltersComponent implements OnInit {

@ViewChild(ResultAreaDirective) resultArea!: ResultAreaDirective

constructor(private resolver: ComponentFactoryResolver) { }

ngOnInit(): void {
}

loadMore() {
const viewContainerRef = this.resultArea.viewContainerRef;
const factory = this.resolver.resolveComponentFactory(RecentGridComponent)
const componentRef = viewContainerRef.createComponent<RecentGridComponent>(factory)
}

}

最佳答案

正如 yurzui 所指出的,v12 的正确规范是 here

要直接通过类(class),应该使用 v13。

关于javascript - 如何在 Angular 12 中动态加载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69875608/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com