簡體   English   中英

Angular 5 添加組件的新實例

[英]Angular 5 Adding a new instance of a component

我正在使用 angular 5,我想按需創建組件的新實例。

這是我目前擁有的代碼:

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

應用程序組件.html

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

我的組件.html:

<div>I am MyComponent</div>

我怎樣才能做到這一點?

這是您自己創建組件的方法:(別忘了銷毀它!在componentRef上調用destroy()可以做到這一點)

父組件:

@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:

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

您可以在父組件中使用數組,並在每次單擊add按鈕時增大數組。 在您的app.component.html使用ngFor循環來迭代數組,然后在循環中使用MyComponent上定義的選擇器,該選擇器將為每次迭代添加一個新實例。

請記住,您永遠不會解釋為什么要執行此操作,這樣就不會傳遞任何數據,並且沒有人會說哪種方法是執行此操作的最佳方法,而不知道您想如何與創建的組件進行交互。

app.component.ts:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  myComponents:any[] = [];

  constructor() {}
  addCmp() {
    console.log('adding');
    this.myComponents.push(null);
  }
}

app.component.html

<button (click)="addCmp()" >Add New MyComponent below</button>
<ng-container *ngFor="let i of myComponents">
  <my-component></my-component>
</ng-container>

也許您應該使用此方法。 我在單元測試中使用它。

let component:MyComponent = new MyComponent();

現在,您可以通過組件變量訪問MyComponent的屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM