简体   繁体   中英

Dependency Injection problem for creating dynamic components with ngComponentOutlet

The project requires to create components dynamically by using ngComponentOutlet directive. The dynamic components will receive data by injecting it into the constructor. So, how can I pass this data as a parameter in the constructor?

I have created a sample and the link is https://angular-lqaeqp.stackblitz.io/load

The project structure is:

  1. HomeComponent - The starting point

  2. LoadComponents Module - A lazy loaded module which has 2 components

    (i) LoadComponents - The default for route '/load'

    (ii) Component1Component - The dynamic component that will be created from LoadComponents

The LoadComponents has the following code for the creation:

<ng-container *ngComponentOutlet="component;injector: injectData;"></ng-container>

  1. Content Model - A model that needs to be injected in Component1Component

If I remove the injection code then the app works, otherwise it shows the error:

Error: StaticInjectorError(AppModule)[Component1Component -> Content]

For the time being I have solved the project issue by using the plugin "ng-dynamic-component", which works like a charm. But I have to apply Angular's ngComponentOutlet directive.

You are injecting Content to your component, therefore it should be an injectable:

@Injectable({
  providedIn: 'root',
})
export class Content {
    @Input() public Code: string;
    @Input() public HTML: string;
}

Your fixed StackBlitz

PS. Always include the troubling code in your question!

Service and Component are different purpose in Angular

Service is a broad category encompassing any value, function, or feature that an app needs. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.

Angular distinguishes components from services to increase modularity and reusability. By separating a component's view-related functionality from other kinds of processing, you can make your component classes lean and efficient.

Since you are Using Injectable decorator inside content.module.ts you should not use @Input decorator. Then don't initialize Object with new Key word. Instantiating an object with new keyword is used to create objects that are not injectable. Ref: Angular2 - calling constructor() vs new keyword to create an object?

content.model.ts

import { Injectable } from '@angular/core';    
@Injectable({
  providedIn: 'root',
})
export class Content {
   Code: string ;
   HTML: string;
}

Example: https://stackblitz.com/edit/angular-favvmz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM