Ranjan
Ranjan

Reputation: 475

Angular 2 - get child component to load inside parent component(getting created dynamically)

I am trying to dynamically create a header, constructing and passing the header template as 'string' to my dynamic component. My requirement is to call another component inside the header component template string and load it.

Have created a working Plunker here for the scenario.

I get an error in the browser console as:

Unhandled Promise rejection: Template parse errors:
'alert' is not a known element:
1. If 'alert' is an Angular component, then verify that it is part of this module.
2. If 'alert' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("     <span class="title" style="float: right; margin-right: 10px;">
                                [ERROR ->]<alert></alert>   
                                <img class="notify-circle" src="https://cdn0.iconf"): DynamicComponent@2:32 ; Zone: <root> ; Task: Promise.then ; Value: Object { _nativeError: Error, stack: "" } BaseError@https://unpkg.com/@angular/compiler/bundles/compiler.umd.js:1595:29 [angular]

Question:

How can i get the 'Alert' component recognized inside the header template constructed as a string, using the selector '<alert></alert>'.

The concept may seem bizarre, but the requirement is such.

Upvotes: 2

Views: 1884

Answers (1)

yurzui
yurzui

Reputation: 214295

You can create special shared module that contains always what you need

@NgModule({
  declarations: [AlertComponent],
  exports: [AlertComponent]
})
export class SharedDynamicModule {}

and then import it to your DynamicModule

dynamic.ts

@NgModule({
  imports: [ CommonModule, SharedDynamicModule ],
  declarations: [ DynamicComponent ]
})
class DynamicHtmlModule { }

Modified Plunker

Upvotes: 2

Related Questions