Angular 5添加组件的新实例 [英] Angular 5 Adding a new instance of a component

查看:143
本文介绍了Angular 5添加组件的新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angular 5,我想按需创建组件的新实例。

I am using angular 5 and I want to create new instances of a component on demand.

这是我目前的代码:

app.component.ts:

app.component.ts:

import { Component } from '@angular/core';
import { MyComponent } from './mycomp/my.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  constructor() {}
  addCmp() {
    console.log('adding');
    // Add an instance of MyComponent code goes here ?
  }
}

app.component.html

app.component.html

<button (click)="addCmp()" >Add New MyComponent below</button>

MyComponent.html:

MyComponent.html:

<div>I am MyComponent</div>

我该怎么做?

推荐答案

这是通过自己创建组件的方法:
(别忘了销毁它!在componentRef上调用destroy()来执行此操作)

This is the way to create a component by your self: (Don't forget to destroy it! call destroy() on the componentRef to do this)

父组件:

@ViewChild('componentHolder', { read: ViewContainerRef }) componentHolder: ViewContainerRef;

constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

public createComponent(): void {
          const componentFactory = this.componentFactoryResolver.resolveComponentFactory(MyComponent);
          const componentRef = this.componentHolder.createComponent(componentFactory);
}

父组件HTML:

<button (click)="createComponent()">Add New MyComponent below</button>
<div #componentHolder ></div>

在NgModule中添加MyComponent:

Add the MyComponent in the NgModule:

...
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes),
  ],
  entryComponents: [
    MyComponent
  ],...

这篇关于Angular 5添加组件的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆