Внедрение Injector и использование его с createComponent.
Вручную предоставление зависимостей в модуле, где объявлен компонент.
Код: Выделить всё
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { LoggingService } from './logging.service';
@Component({
selector: 'app-dynamic',
template: `
Dynamic Component Loaded!
`,
})
export class DynamicComponent {
constructor(private http: HttpClient, private loggingService: LoggingService) {
console.log('DynamicComponent initialized with HttpClient and LoggingService');
}
}
import {
Component,
ComponentRef,
Injector,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import { DynamicComponent } from './dynamic.component';
@Component({
selector: 'app-root',
template: `Load Dynamic Component
`,
})
export class AppComponent {
@ViewChild('container', { read: ViewContainerRef, static: true })
container!: ViewContainerRef;
constructor(private injector: Injector) {}
loadComponent() {
const componentRef: ComponentRef = this.container.createComponent(DynamicComponent, {
injector: this.injector, // Provide the injector to resolve dependencies
});
const instance = componentRef.instance;
console.log('Dynamic component instance:', instance);
}
}
[*]Решение, позволяющее осуществлять динамический рендеринг компонента с правильным внедрением зависимостей.< /li>
Подход, который не ставит под угрозу модульность и позволяет избежать ручного управления зависимостями.
[*]Бонус: как добавить собственные поставщики в динамически создаваемый компонент.
>
Подробнее здесь: https://stackoverflow.com/questions/793 ... dencies-in
Мобильная версия