javascript - Bir bileşeni diğerine dinamik olarak ekleme
İşte benim stackblitz bağlantım: DEMO
Görselleştirme türü 'tablo' olduğunda, 'table' bileşenini app bileşeninin #test içine eklemeye çalışıyorum. Bunun için, #test div'ine <app-table> etiketlerini oluşturan ve ekleyen createTable() fonksiyonunu çağırıyorum.
<app-table> etiketi DOM'da mevcut ama table.component.html içeriği değil (yani, tablo çalışıyor!) Bu, onun sadece bir etiket ve derlenmiş bir bileşen olmamasından kaynaklanabilir.
Uygulama bileşeni içinde görüntülenen tablo bileşeninin içeriğini nasıl alırım?
Cevap #1
Bunu dene
createTable() {
this.container.clear();
const factory = this.resolver.resolveComponentFactory(TableComponent);
this.componentRef = this.container.createComponent(factory);
}
Sizin Çatallanmış Örneğiniz: https://stackblitz.com/edit/dashboard-inchara-3xrjkj
Cevap #2
ComponentFactoryResolver'ı bileşenleri dinamik olarak eklemek için kullanın. Bu, Angular Belgelerinde daha ayrıntılı olarak açıklanmıştır. Stackblitz'te tam bir çözüm ekledim: ComponentFactoryResolver. Özetle yaptığım şunlardır:
app.component.ts dosyasında tablo oluşturma:
createTable(container) {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(TableComponent);
let viewContainerRef = this.insTable.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
// let e = document.createElement("app-table");
// container.appendChild(e);
}
Çapa noktası olarak kullanılan yönerge table.directive.ts:
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[ins-table]',
})
export class TableDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
Ve app.component.html:
<div #charts id="test">
<ng-template ins-table></ng-template>
</div>
Ve her şeyin çalışması için uygun beyanlarla app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ChartModule } from 'angular-highcharts';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { TableComponent } from './table/table.component';
import { TableDirective } from './table/table.directive';
@NgModule({
imports: [BrowserModule, ChartModule, HttpClientModule],
declarations: [AppComponent, TableComponent, TableDirective],
bootstrap: [AppComponent],
providers: [HttpClientModule],
entryComponents: [
TableComponent
]
})
export class AppModule { }
