如何通过for循环添加html组件,html – 动态添加和删除Angular中的组件

您可以通过使用ComponentFactoryResolver动态创建组件然后将它们注入ViewContainerRef来完成您要实现的目标.动态执行此操作的一种方法是将组件的类作为函数的参数传递,该函数将创建并注入组件.

见下面的例子:

import {

Component,

ComponentFactoryResolver, Type,

ViewChild,

ViewContainerRef

} from '@angular/core';

// Example component (can be any component e.g. app-header app-section)

import { DraggableComponent } from './components/draggable/draggable.component';

@Component({

selector: 'app-root',

template: `

Add

Remove

`

})

export class AppComponent {

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

// Keep track of list of generated components for removal purposes

components = [];

// Expose class so that it can be used in the template

draggableComponentClass = DraggableComponent;

constructor(private componentFactoryResolver: ComponentFactoryResolver) {

}

addComponent(componentClass: Type) {

// Create component dynamically inside the ng-template

const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentClass);

const component = this.container.createComponent(componentFactory);

// Push the component so that we can keep track of which components are created

this.components.push(component);

}

removeComponent(componentClass: Type) {

// Find the component

const component = this.components.find((component) => component.instance instanceof componentClass);

const componentIndex = this.components.indexOf(component);

if (componentIndex !== -1) {

// Remove component from both view and array

this.container.remove(this.container.indexOf(component));

this.components.splice(componentIndex, 1);

}

}

}

笔记:

>如果您希望以后更容易删除组件,可以在局部变量中跟踪它们,请参阅this.components.或者,您可以遍历ViewContainerRef中的所有元素.

>您必须将组件注册为条目组件.在模块定义中,将组件注册为entryComponent(entryComponents:[DraggableComponent]).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值