将子组件附加到角组件的父组件中

时间:2018-07-20 21:07:44

标签: angular typescript

我正在寻找一种干净的方法in a jquery append-like fashion,每次给定事件触发时,将子组件child动态附加到父组件parent上,以便从:

<parent></parent>

我会得到:

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

此外,在事件发生之前,必须将子组件的类型视为未知。

我想结构可以像这样建模:

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

}

使用jQuery,我将以以下方式进行操作:

<div id="parent"></div>

脚本:

document.body.onmyevent = function(e, n) {
    if(n%2==0){
        child = $("div.even-child")
    } else {
        child = $("div.odd-child")
    }
    $("#parent").append(child)
}

当激发带有参数n=4的事件时,我会实现:

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

我该如何实现?

1 个答案:

答案 0 :(得分:0)

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>

现在要触发该事件,您可以执行以下操作: this.showEvent.emit("item type 1") 但我认为您将在父组件之外使用此事件,如果需要,则需要服务