How can I add component dynamically?
toolbar.component.ts:
@Component({
selector: 'app-toolbar',
template: '<button>Add Text component</button>'
})
export class ToolbarComponent {
constructor() { }
}
section.component.ts:
@Component({
selector: 'div[app-type=section]',
template: ''
})
export class SectionComponent {
constructor() { }
}
text.component.ts:
@Component({
selector: 'app-text',
template: '<p>This is dynamically component</p>'
})
export class TextComponent {
constructor() { }
}
view.component.ts:
@Component({
selector: 'app-view',
template: `<div class="container">
<app-toolbar></app-toolbar>
<div app-type="section" id="SECTION1" class="active"></div>
<div app-type="section" id="SECTION2"></div>
</div>`
})
export class SectionComponent {}
when I click to ToolBarComponent, I want to add TextComponent to SectionComponent which have "active" class.
Expose
viewContainerRef
on section.component.ts:Add an output to toolbar.component.ts:
In view.component.ts create a
ComponentFactory
for TextComponents to add them dynamically to active SectionComponents:StackBlitz example
I would do it using ngFor view.component.ts:
toolbar.component.ts: