Reputation: 562
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:
HomeComponent - The starting point
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>
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.
Upvotes: 0
Views: 885
Reputation: 27461
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
Upvotes: 1
Reputation: 73367
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!
Upvotes: 1