【问题标题】:add component on click of button in angular 7/8在 Angular 7/8 中单击按钮时添加组件
【发布时间】:2020-03-21 21:00:52
【问题描述】:

我有一个可以在单击按钮时导入的通用组件。

在该组件中有一些常见的 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】:

    试试这个:

    ...
    @ViewChild('appenHere', {static : false, read : ViewContainerRef}) target: ViewContainerRef;
    private componentRef: ComponentRef<any>;
    ...
    

    Working Demo

    【讨论】:

    • 仍然出现错误:错误类型错误:无法读取未定义的属性“createComponent”。我正在使用角度 8
    • 它不适用于动态数据。它没有显示在单个选项卡中。我有 3 个标签。所有 3 个选项卡都包含该按钮,当我单击第一个选项卡的 btn 时,它正在添加该组件,但是当我单击第二个选项卡的同一个按钮时,它仅在第一个选项卡中添加该组件,它应该添加到第二个选项卡中。
    • static : true 不适用于动态引用,对于另一个要求,请打开一个具有确切标题/解释的新请求。
    【解决方案2】:

    这是你的分叉StackBlitz link

    改变这一行

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

    更多参考请参考StackOverFlow Link

    【讨论】:

    • 它不适用于动态数据。它没有显示在单个选项卡中。我有 3 个标签。所有 3 个选项卡都包含该按钮,当我单击第一个选项卡的 btn 时,它正在添加该组件,但是当我单击第二个选项卡的同一个按钮时,它仅在第一个选项卡中添加该组件,它应该添加到第二个选项卡中。
    猜你喜欢
    • 1970-01-01
    • 2020-03-01
    • 2021-09-26
    • 2020-12-24
    • 2021-06-28
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多