单击角7/8时单击按钮添加组件

问题描述 投票:0回答:1

我有一个公共组件,单击按钮时可以将其导入。在该组件中有常见的html:

这里是stackblitz

当我单击按钮时,出现以下错误:

错误:无法读取未定义的属性'createComponent'

app.component.html:

<div class="row" #appenHere></div>
<div>
   <button (click)="addNewComponent()">Append</button>
</div>

app.component.ts:

import { Component, OnInit, TemplateRef, ViewChild, AfterViewInit, Inject, ViewContainerRef, ComponentFactoryResolver, ComponentRef } from '@angular/core';
import { NewTileComponent } from './new-tile/new-tile.component';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {

  @ViewChild('appenHere') target: ViewContainerRef;
  private componentRef: ComponentRef<any>;

  constructor(private resolver: ComponentFactoryResolver) { }

  addNewComponent() {
    let childComponent = this.resolver.resolveComponentFactory(NewTileComponent);
    this.componentRef = this.target.createComponent(childComponent); <-- here it's throws an error!
  }

}

new-tile.component.html:

<p>This is new</p>
angular components angular7 angular8 angular-dynamic-components
1个回答
0
投票

尝试一下:

...
@ViewChild('appenHere', {read : ViewContainerRef}) target: ViewContainerRef;
private componentRef: ComponentRef<any>;
...
© www.soinside.com 2019 - 2024. All rights reserved.