I am looking for a neat solution to dynamically add a child component child
to a parent component parent
, using a method similar to jQuery's append
. This should happen every time a specific event occurs. Ideally, starting with:
<parent></parent>
The goal is to end up with:
<parent>
<child></child>
</parent>
It's worth noting that the type of the child component will not be known until the event triggers.
A possible structure could be defined as follows:
import { Component} from '@angular/core';
import { OnMyEvent} from 'onmyevent';
@Component({selector: 'odd-child'})
export class OddChildComponent {}
@Component({selector: 'even-child'})
export class EvenChildComponent {}
@Component({selector: 'parent'})
export class ParentComponent implements OnMyEvent {
constructor() {}
onMyEvent(n) {
if (n%2==0){
this.append(new EvenChildComponent())
} else {
this.append(new OddChildComponent())
}
}
}
With jQuery, the process would look something like this:
<div id="parent"></div>
Script:
document.body.onmyevent = function(e, n) {
if(n%2==0){
child = $("div.even-child")
} else {
child = $("div.odd-child")
}
$("#parent").append(child)
}
If the event with parameter n=4
is triggered, the result would be:
<div id="parent">
<div class="even-child"></div>
</div>
How can this functionality be achieved?