1

I have this plunker example https://embed.plnkr.co/RtZvxv2rPFpLPZGndS0g/ where I have two components created on the fly: ContentComponent and HeaderComponent. I want to reference the HeaderComponent selector in the ContentComponent template like this:

ngOnInit() {
  this.template = "<div>This is the {{ name }}</div><app-header></app-header>";
  this.compileTemplate();
}

Unfortunately this is not working and the compiler complains: app-header is not a known element.

Does anyone have an idea how to solve this problem? Is there another way to obtain the same end result?

6
  • You can't add Angular "stuff" like that at runtime - only plain HTML. For what you want you would need to compile a component at runtime. See stackoverflow.com/questions/38888008/… Commented Nov 22, 2017 at 13:15
  • 2
    plnkr.co/edit/2zMCh6elJxh2RInqB6ZZ?p=preview Commented Nov 22, 2017 at 13:20
  • 1
    did @yurzui's solution help? Commented Nov 22, 2017 at 13:31
  • It is finally working! Thank you very much @yurzui! Commented Nov 22, 2017 at 14:37
  • Thank you @AngularInDepth.com for teaching me how to use dynamic components. It is amazing what you can do with Angular today. blog.angularindepth.com/… Commented Nov 22, 2017 at 14:38

1 Answer 1

2

Angular can't find app-header element because HeaderComponent was neither declared nor imported

To solve it you can create SharedModule that declares and exports HeaderComponent

@NgModule({
    declarations: [ HeaderComponent],
    exports: [HeaderComponent]
})
export class SharedModule { }

and finally simply import it in your dynamic module

@NgModule({
  declarations: [decoratedCmp], 
  imports: [SharedModule] <============ this line
})
class RuntimeContentModule { }

Plunker Example

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.