簡體   English   中英

單擊按鈕時創建一個組件,Angular 13

[英]creating a component when i click button, Angular 13

當我使用 Angular 單擊按鈕時如何創建組件 13 我嘗試的方法是使用 ViewChild 和 ComponentFactoryResolver 仍然感到困惑 還有沒有其他方法

import {
  Component,
  OnInit,
  TemplateRef,
  ViewChild,
  AfterViewInit,
  Inject,
  ViewContainerRef,
  ComponentFactoryResolver,
  ComponentRef,
} from '@angular/core';

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

  @ViewChild('appenHere', {static : false, read : ViewContainerRef}) 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!
  } 
}


對於 Angular v13 及更高版本

Angular v13中, ComponentResolveFactory被標記為已棄用,並將在v16中刪除。

引入了動態創建組件的新方法。

這是一個代碼示例:

import { Component, ViewChild, ViewContainerRef } from '@angular/core';

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

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

  constructor() { }

  addNewComponent() {
    this.target.createComponent(NewTileComponent);
  } 
}

暫無
暫無

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

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