Spec-Zone.ru › Angular

NgComponentOutlet

Создаёт экземпляр типа Component и вставляет его представление-хост в текущее представление. NgComponentOutlet предоставляет декларативный подход к динамическому созданию компонентов.

Использование NgComponentOutlet

API

class NgComponentOutlet<T = any> implements OnChanges ,DoCheck ,OnDestroy {
  constructor(_viewContainerRef: ViewContainerRef): NgComponentOutlet<T>;
  @Input() ngComponentOutlet: Type<T> | null;
  @Input() ngComponentOutletInputs?: Record<string, unknown> | undefined;
  @Input() ngComponentOutletInjector?: Injector | undefined;
  @Input() ngComponentOutletEnvironmentInjector?: EnvironmentInjector | undefined;
  @Input() ngComponentOutletContent?: Node[][] | undefined;
  @Input() ngComponentOutletNgModule?: Type<any> | undefined;
  readonly componentInstance: T | null;
}

constructor

NgComponentOutlet<T>
@param_viewContainerRefViewContainerRef
@returnsNgComponentOutlet<T>

ngComponentOutlet

Type<T> | null

Компонент, который следует отобразить в точке вставки.

ngComponentOutletInputs

Record<string, unknown> | undefined

ngComponentOutletInjector

Injector | undefined

ngComponentOutletEnvironmentInjector

EnvironmentInjector | undefined

ngComponentOutletContent

Node[][] | undefined

ngComponentOutletNgModule

Type<any> | undefined

componentInstance

T | null

Возвращает экземпляр отображаемого в данный момент компонента. Если компонент не отображается, возвращает null.

Описание

Создаёт экземпляр типа Component и вставляет его представление-хост в текущее представление. NgComponentOutlet предоставляет декларативный подход к динамическому созданию компонентов.

Для NgComponentOutlet требуется тип компонента. Если указано ложное значение, представление будет очищено, а все существующие компоненты уничтожены.


Экспортируется модулем

  • CommonModule

Примечания по использованию

Точная настройка управления

Вы можете управлять процессом создания компонента с помощью следующих необязательных атрибутов:

  • ngComponentOutletInputs: Необязательный объект входных данных компонента, который будет привязан к компоненту.

  • ngComponentOutletInjector: Необязательный пользовательский Injector, который будет использоваться в качестве родительского для компонента. По умолчанию используется инжектор текущего контейнера представления.

  • ngComponentOutletEnvironmentInjector: Необязательный пользовательский EnvironmentInjector, который предоставляет окружение компонента.

  • ngComponentOutletContent: Необязательный список проецируемых узлов для вставки в секцию содержимого компонента, если она существует.

  • ngComponentOutletNgModule: Необязательная ссылка на класс NgModule, позволяющая динамически загрузить другой модуль, а затем загрузить компонент из этого модуля.

Синтаксис

Простой вариант

<ng-container *ngComponentOutlet="componentTypeExpression"></ng-container>

С входными данными

<ng-container *ngComponentOutlet="componentTypeExpression;
                                  inputs: inputsExpression;">
</ng-container>

Настраиваемый инжектор/содержимое

<ng-container *ngComponentOutlet="componentTypeExpression;
                                  injector: injectorExpression;
                                  content: contentNodesExpression;">
</ng-container>

Настраиваемая ссылка на NgModule

<ng-container *ngComponentOutlet="componentTypeExpression;
                                  ngModule: ngModuleClass;">
</ng-container>

Простой пример

@Component({
  selector: 'hello-world',
  template: 'Hello World!',
})
export class HelloWorld {}

@Component({
  selector: 'ng-component-outlet-simple-example',
  imports: [NgComponentOutlet],
  template: `<ng-container *ngComponentOutlet="HelloWorld"></ng-container>`,
})
export class NgComponentOutletSimpleExample {
  // This field is necessary to expose HelloWorld to the template.
  HelloWorld = HelloWorld;
}

Более полный пример с дополнительными параметрами:

@Injectable()
export class Greeter {
  suffix = '!';
}

@Component({
  selector: 'complete-component',
  template: `{{ label() }}: <ng-content></ng-content> <ng-content></ng-content
    >{{ greeter.suffix }}`,
})
export class CompleteComponent {
  label = input.required<string>();

  constructor(public greeter: Greeter) {}
}

@Component({
  selector: 'ng-component-outlet-complete-example',
  imports: [NgComponentOutlet],
  template: ` <ng-template #ahoj>Ahoj</ng-template>
    <ng-template #svet>Svet</ng-template>
    <ng-container
      *ngComponentOutlet="
        CompleteComponent;
        inputs: myInputs;
        injector: myInjector;
        content: myContent
      "
    ></ng-container>`,
})
export class NgComponentOutletCompleteExample {
  // This field is necessary to expose CompleteComponent to the template.
  CompleteComponent = CompleteComponent;

  myInputs = {'label': 'Complete'};

  myInjector: Injector;
  ahojTemplateRef = viewChild.required<TemplateRef<any>>('ahoj');
  svetTemplateRef = viewChild.required<TemplateRef<any>>('svet');
  myContent?: any[][];

  constructor(
    injector: Injector,
    private vcr: ViewContainerRef,
  ) {
    this.myInjector = Injector.create({
      providers: [{provide: Greeter, deps: []}],
      parent: injector,
    });

    effect(() => {
      this.myContent = [
        this.vcr.createEmbeddedView(this.ahojTemplateRef()).rootNodes,
        this.vcr.createEmbeddedView(this.svetTemplateRef()).rootNodes,
      ];
    });
  }
}

Super-powered by Google ©2010–2025.
Code licensed under an MIT-style License. Documentation licensed under CC BY 4.0.
https://angular.dev/api/common/NgComponentOutlet

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API