弄個按鈕按一下會新增一個component
然後把邏輯抽出去一個service
搞出第二顆按鈕
再放個上下移動處理順序
@Component({
selector: 'app-dynamic-component-container',
standalone: true,
imports: [CommonModule],
template: '<ng-container #container></ng-container>',
})
export class DynamicComponentContainerComponent {
@ViewChild('container', { read: ViewContainerRef, static: true })
container!: ViewContainerRef;
components: ComponentRef<any>[] = [];
constructor() { }
loadComponent(component: Type<any>, templateRef: any) {
const componentRef: ComponentRef<{ template: TemplateRef<any>, context: any }> = this.container.createComponent(component);
componentRef.instance.template = templateRef;
componentRef.instance.context = { data: this.components.length }; // 設定 context
this.components.push(componentRef);
}
moveUp(index: number) {
if (index > 0) {
const temp = this.components[index];
this.components[index] = this.components[index - 1];
this.components[index - 1] = temp;
this.renderComponents();
}
}
moveDown(index: number) {
if (index < this.components.length - 1) {
const temp = this.components[index];
this.components[index] = this.components[index + 1];
this.components[index + 1] = temp;
this.renderComponents();
}
}
private renderComponents() {
this.container.clear();
this.components.forEach((component) =>
this.container.insert(component.hostView)
);
}
}
@Component({
selector: "app-root",
standalone: true,
template: `
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" (click)="loadComponent(MyComponent1)">Load Component 1</button>
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" (click)="loadComponent(MyComponent2)">Load Component 2</button>
<div>
<app-dynamic-component-container></app-dynamic-component-container>
</div>
<ng-template #name let-index='index'>
<p>Template content: {{ index }}</p>
<div>
<button (click)="dynamicComponentContainer.moveUp(index)">
Move Up
</button>
<button (click)="dynamicComponentContainer.moveDown(index)">
Move Down
</button>
</div>
</ng-template>
`,
styles: `.flex{
display:flex;
}`,
imports: [DynamicComponentContainerComponent, MyComponent2, MyComponent1],
})
export class App {
@ViewChild('name') templateRef!: TemplateRef<any>;
@ViewChild(DynamicComponentContainerComponent, {
read: DynamicComponentContainerComponent,
static: false,
})
dynamicComponentContainer!: DynamicComponentContainerComponent;
name = "Angular";
MyComponent1 = MyComponent1;
MyComponent2 = MyComponent2;
constructor() { }
loadComponent(component: any) {
this.dynamicComponentContainer.loadComponent(component, this.templateRef);
}
}