gpt4 book ai didi

angular - 以 2/4 Angular 动态添加组件

转载 作者:行者123 更新时间:2023-12-04 14:33:09 29 4
gpt4 key购买 nike

如何动态添加组件?

工具栏.组件.ts:

@Component({
selector: 'app-toolbar',
template: '<button>Add Text component</button>'
})
export class ToolbarComponent {
constructor() { }
}

section.component.ts:
@Component({
selector: 'div[app-type=section]',
template: ''
})
export class SectionComponent {
constructor() { }
}

text.component.ts:
@Component({
selector: 'app-text',
template: '<p>This is dynamically component</p>'
})
export class TextComponent {
constructor() { }
}

view.component.ts:
@Component({
selector: 'app-view',
template: `<div class="container">
<app-toolbar></app-toolbar>
<div app-type="section" id="SECTION1" class="active"></div>
<div app-type="section" id="SECTION2"></div>
</div>`
})
export class SectionComponent {}

当我单击 ToolBarComponent 时,我想将 TextComponent 添加到具有“事件”类的 SectionComponent。

最佳答案

曝光 viewContainerRef section.component.ts :

@Component({
selector: 'div[app-type=section]',
template: ''
})
export class SectionComponent {
@Input() active: boolean;

constructor(public viewContainerRef: ViewContainerRef) { }
}

将输出添加到 工具栏.component.ts :
@Component({
selector: 'app-toolbar',
template: '<button (click)="addComponentClick.emit()">Add Text component</button>'
})
export class ToolbarComponent {
@Output() addComponentClick = new EventEmitter();
constructor() { }
}

view.component.ts 创建 ComponentFactory用于 TextComponents 将它们动态添加到 事件 部分组成:
import { Component, AfterViewInit, ViewChildren, QueryList, ElementRef, ComponentFactoryResolver, ComponentFactory, OnInit } from '@angular/core';
import { TextComponent } from './text.component';
import { SectionComponent } from './section.component';

@Component({
selector: 'app-view',
template: `<div class="container">
<app-toolbar (addComponentClick)="onAddComponentClick()"></app-toolbar>
<div app-type="section" id="SECTION1" [active]="true"></div>
<div app-type="section" id="SECTION2"></div>
</div>`
})
export class ViewComponent implements AfterViewInit, OnInit {
@ViewChildren(SectionComponent) sections: QueryList<SectionComponent>;
activeSections: SectionComponent[];
textComponentFactory: ComponentFactory<TextComponent>;

constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

ngOnInit() {
this.textComponentFactory = this.componentFactoryResolver.resolveComponentFactory(TextComponent);
}

ngAfterViewInit() {
this.activeSections = this.sections.reduce((result, section, index) => {
if(section.active) {
result.push(section);
}
return result;
}, []);
}

onAddComponentClick() {
this.activeSections.forEach((section) => {
section.viewContainerRef.createComponent(this.textComponentFactory);
});
}
}

StackBlitz example

关于angular - 以 2/4 Angular 动态添加组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49079989/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com