Я пытаюсь динамически загрузить компонент в ViewContainerRef, а конструктор компонента зависит от нескольких служб (например, HttpClient, специальной службы и т. д.). Однако я получаю сообщение об ошибке, связанное с отсутствием поставщиков. Вот что я пробовал до сих пор:
Внедрение 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);
}
}
What I Am Looking For:
A solution that allows dynamic rendering of a component with proper dependency injection.
An approach that does not compromise modularity and avoids manual dependency management.
Bonus: How to add custom providers to a dynamically created component.
Подробнее здесь: https://stackoverflow.com/questions/793 ... dencies-in
Как я могу динамически визуализировать компонент в Angular со сложными зависимостями, введенными в его конструктор? ⇐ CSS
Разбираемся в CSS
1736534798
Anonymous
Я пытаюсь динамически загрузить компонент в ViewContainerRef, а конструктор компонента зависит от нескольких служб (например, HttpClient, специальной службы и т. д.). Однако я получаю сообщение об ошибке, связанное с отсутствием поставщиков. Вот что я пробовал до сих пор:
Внедрение 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);
}
}
What I Am Looking For:
A solution that allows dynamic rendering of a component with proper dependency injection.
An approach that does not compromise modularity and avoids manual dependency management.
Bonus: How to add custom providers to a dynamically created component.
Подробнее здесь: [url]https://stackoverflow.com/questions/79346732/how-can-i-dynamically-render-a-component-in-angular-with-complex-dependencies-in[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия