Lars
Lars

Reputation: 1092

How to use Pipes in Angular dynamic loaded components?

I need to load several components in a dynamic way. That is why I have created a parent component to do the job (depending on the value of this.rink), like:

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();
}

This works well, but for what reason ever I'm not able to use any pipes inside the HTML template of templateFreetext.

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

This returns Error: The pipe 'date' could not be found!

My question is now how I can use dynamic created components and pipes? What did I forget?

Upvotes: 2

Views: 825

Answers (2)

Kris Zeufr
Kris Zeufr

Reputation: 1

It seems that Pipes are not working right now using this method, as we can see here (on universal, but i have the same behavior on another project): https://github.com/angular/universal/issues/1878

You can use the declarations to bypass the problem for the moment

Upvotes: 0

firasKoubaa
firasKoubaa

Reputation: 6867

you may declare your dynamic components as declarations of a specific separated module , without exporting them in it (you may call it dynamicElementsModule) , and then import this module in the appModule

Like that you can use any toool in the commonModule (such as pipes)

@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 {}

Finally you can use the pipes :

dynamic.component.ts

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

  ngOnInit() {}
}

dynamic.component.html

{{ customDataInputs | json }}

Here is a full working snippet

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

Upvotes: 0

Related Questions