简体   繁体   中英

Append child component to parent component in angular

I am searching for a clean way, in a jquery append -like fashion , to dynamically append an child component child to a parent component parent , every time a given event fires, so that, starting from:

<parent></parent>

I would get:

<parent>
   <child></child>
</parent>

Also, the component type of the child have to be considered unknown until the event happens.

I suppose the structure could be modelled like:

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())
    }
  }

}

Using jquery I would go about this in the following fashion:

<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)
}

And when the event with parameter n=4 is fired I would achieve:

<div id="parent">
    <div class="even-child"></div>
</div>

How do I achieve this?

import {EventEmitter, OnInit} from "@angular/core";
@Component({selector: 'parent'})
export class ParentComponent implements OnInit{
  item = null
  showEvent: EventEmitter<string>;
  constructor() {
   this.showEvent = new EventEmitter<string>();
  }
  ngOnInit(){
   this.showEvent.subscribe(item=> {
      this.item = item;
   })
  }

}

<parent>
   <child *ngIf="item === 'item type 1'"></child>
   <another-child *ngIf="item === 'item type 2'"></another-child>
</parent>

now to trigger that event you do: this.showEvent.emit("item type 1") but i think you are going to use this event outside of the parent component, if so, you need a service

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM