【问题标题】:How to use Pipes in Angular dynamic loaded components?如何在 Angular 动态加载组件中使用管道?
【发布时间】:2020-10-29 22:01:22
【问题描述】:

我需要以动态方式加载多个组件。这就是为什么我创建了一个父组件来完成这项工作(取决于this.rink 的值),例如:

ngAfterViewInit() {
    switch (this.rink) {
        case 'ITCO':
            this.templateFreetext = FreetextITCOComponent;
            break;

        case 'INH':
            this.templateFreetext = FreetextINHComponent;
            break;

        default:
            this.templateFreetext = FreetextBERComponent;
            break;
    }

    const cfr = AppInjector.get(ComponentFactoryResolver);
    const factory = cfr.resolveComponentFactory(this.templateFreetext);
    this.componentRef = container.createComponent(factory);
    
    this.componentRef.instance.data = data;
    this.componentRef.changeDetectorRef.detectChanges();
}

这很好用,但出于什么原因,我无法在templateFreetext 的 HTML 模板中使用任何管道。

    ...
    <div class="text-right text-warning">
        {{ data.day | date:'EEEE, dd.MM.yyyy' }}
    </div>
    ...

这会返回Error: The pipe 'date' could not be found!

我现在的问题是如何使用动态创建的组件和管道?我忘记了什么?

【问题讨论】:

  • 您使用哪个版本的 Angular?我在使用 Ivy 迁移到 NG9 时遇到了这个问题。在 NG9 之前,您必须将动态组件添加到模块中的“entryComponents”。也许这会解决它?
  • @T.vandenBerg 我正在使用 NG10。所以我不再有“entryComponents”了
  • 我创建了一个 Blitzstack 来测试它。首先,您应该避免在生命周期挂钩中更改视图。一个技巧是将超时设置为 0,因此它只会在加载完成后应用。 angular-8vztax.stackblitz.io 我确实必须定义 entryComponent。可能是因为我用的是 DI。
  • 同样的问题;你找到解决办法了吗?

标签: angular angular-pipe angular-dynamic-components


【解决方案1】:

您可以将您的动态组件声明为特定分离模块的声明,而不在其中导出它们(您可以将其称为dynamicElementsModule),然后将该模块导入appModule

就像你可以使用commonModule中的任何工具(比如管道)

@NgModule({
  imports: [CommonModule],
  declarations: [
    // You may here import you dynamic components
    FirstDynamicComponent,
  ],
})
export class DynamicElementssModule {}

app.module.ts

import { DynamicElementssModule } from './dynamic-elements/dynamic-elements.module';

    @NgModule({
      imports: [CommonModule, BrowserModule, FormsModule, DynamicElementssModule],
      declarations: [AppComponent],
      bootstrap: [AppComponent],
    })
    export class AppModule {}

终于可以使用管道了:

dynamic.component.ts

export class FirstDynamicComponent implements OnInit {
  @Input() customDataInputs: any;
  constructor() {}

  ngOnInit() {}
}

dynamic.component.html

{{ customDataInputs | json }}

这是一个完整的工作 sn-p

https://stackblitz.com/edit/angular-ivy-nvjzga?file=src/app/dynamic-elements/first-dynamic-comp/first-dynamic.component.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2019-10-19
    • 2020-11-01
    • 2016-08-17
    • 1970-01-01
    • 2017-01-01
    • 2019-07-04
    相关资源
    最近更新 更多