简体   繁体   English

Angular 4 如何使用 NgComponentOutlet 将数据传递到动态组件

[英]Angular 4 how to pass data into dynamic component with NgComponentOutlet

I fount this similar question.我发现了这个类似的问题。 angular 4+ assign @Input for ngComponentOutlet dynamically created component angular 4+ 为 ngComponentOutlet 动态创建的组件分配 @Input

But it has been about a month.但是已经快一个月了。 Has anything changed?有什么改变吗?

Basically, I followed this guide and created a dynamic component: https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html基本上,我按照本指南创建了一个动态组件: https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

With this approach, I can assign a value to the dynamic component: (<AdComponent>componentRef.instance).data = adItem.data;通过这种方法,我可以为动态组件分配一个值: (<AdComponent>componentRef.instance).data = adItem.data;

Is it still true I can't assign a value to the dynamic component with NgComponentOutlet out of the box?我仍然无法使用开箱即用的 NgComponentOutlet 为动态组件赋值吗? ( https://angular.io/docs/ts/latest/api/common/index/NgComponentOutlet-directive.html ) https://angular.io/docs/ts/latest/api/common/index/NgComponentOutlet-directive.html

You can pass in a custom injector like this - https://github.com/angular/angular/issues/16373#issuecomment-306544456 您可以传递这样的自定义注入器 - https://github.com/angular/angular/issues/16373#issuecomment-306544456

This was kind of a hack so we ended up using this library- 这有点像黑客,所以我们最终使用这个库 -

https://www.npmjs.com/package/ng-dynamic-component https://www.npmjs.com/package/ng-dynamic-component

Worked like a charm! 像魅力一样工作!

In my case, i use ngBaseDef.inputs.data at component. 在我的例子中,我在组件中使用ngBaseDef.inputs.data。

See example: 见例子:


import {Component, Injectable, Input} from '@angular/core';
import {NgbActiveModal, NgbModal} from "@ng-bootstrap/ng-bootstrap";
import {ExampleComponent } from "../components/modals/moder-info/example.component";


@Component({
  selector: 'modal-template',
  template: `
    <div class="modal-header">
      <h4 class="modal-title" [innerText]="title"></h4>
      <button type="button" class="close" aria-label="Close" (click)="close()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <ng-content *ngComponentOutlet="childComponent;"></ng-content>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-outline-dark" (click)="close()">Close</button>
    </div>
  `
})
export class ModalTemplate {
  @Input() title;
  @Input() onClose;
  @Input() childComponent;

  constructor(public activeModal: NgbActiveModal) {}

  close() {
    this.activeModal.dismiss('close');
    this.onClose();
  }
}

export interface ModalServiceOptions {
  data: any;
  title: string
  onClose: any,
  componentName: string
}


@Injectable({
  providedIn: 'root'
})
export class ModalService {
  constructor(private mService: NgbModal) {}

  open(options: ModalServiceOptions) {
    let types = {'example': ExampleComponent };
    let modal = this.mService.open(ModalTemplate, {size: 'lg'});

    modal.componentInstance.title = options.title;
    modal.componentInstance.onClose = options.onClose;

    let component = types[options.componentName];

    component.ngBaseDef.inputs.data = options.data;
    modal.componentInstance.childComponent = types[options.componentName];
  }
}


ExampleComponent ExampleComponent

import {Component, Input, OnInit} from '@angular/core';

@Component({
  selector: 'example-component',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.sass']
})
export class ExampleComponent implements OnInit {
  @Input() data;

  constructor() {
    let dataOfConstructor: any = this.constructor;
    let data = dataOfConstructor.ngBaseDef.inputs.data;
    console.log('data:', data); // Here is my data, i injected it above
  }

  ngOnInit() {
  }

}

Have a nice day! 祝你今天愉快! Hope it helps! 希望能帮助到你!

Basically, there are 2 ways to make the dynamic injection happen.基本上,有两种方法可以实现动态注入。

  1. inject values through the constructor, using a custom (or global) injector: *ngComponentOutlet="myComponent; injector: myInjector , where myInjector is the injector you want to use (if default injector is OK -- take it from your parent's context by adding public myInjector: Injector in your parent component's constructor). That wasn't an option for me as I wanted to keep my dynamic (child) component's constructor clean.通过构造函数注入值,使用自定义(或全局)注入器: *ngComponentOutlet="myComponent; injector: myInjector ,其中myInjector是您要使用的注入器(如果默认注入器正常 - 通过添加从父上下文中获取它public myInjector: Injector in your parent component's constructor). 这对我来说不是一个选择,因为我想保持我的动态(子)组件的构造函数干净。

  2. make a callback that's called when the component is created, and inside that callback assign your @Input values and subscribe your @Output s manually.创建组件时调用的回调,并在该回调中分配您的@Input值并手动订阅您的@Output Now, ngComponentOutlet does not provide any callback functionality, so you may have to reinvent the wheel - create an ngComponentOutlet directive that supports callbacks.现在, ngComponentOutlet不提供任何回调功能,因此您可能不得不重新发明轮子——创建一个支持回调的ngComponentOutlet指令。 And that's exactly what this solution is all about.而这正是该解决方案的全部内容。

I created a custom directive myComponentOutlet ( https://github.com/angular/angular/issues/15360#issuecomment-1070420494 ) - a customizable analogue for ngComponentOutlet .我创建了一个自定义指令myComponentOutlet ( https://github.com/angular/angular/issues/15360#issuecomment-1070420494 ) - ngComponentOutlet的可自定义模拟。 Hopefully, it will eventually make its way to the Angular's src.希望它最终会进入 Angular 的 src。

Here's the directive:这是指令:

import {
  AfterViewInit,
  ComponentFactoryResolver,
  ComponentRef,
  Directive,
  ElementRef,
  EventEmitter,
  Injector,
  Input,
  OnDestroy,
  Output,
  Type,
  ViewContainerRef
} from '@angular/core';

/*
  USAGE:

    <div myComponentOutlet
           [component]="inner.component"
           [injector]="inner.injector"
           (create)="componentCreated($event)"></div>
 */

@Directive({
  selector: '[myComponentOutlet]',
})
export class MyComponentOutletDirective<T> implements AfterViewInit, OnDestroy {

  @Input() component: Type<T>;
  @Input() injector: Injector;
  @Output() create = new EventEmitter<ComponentRef<T>>();
  @Output() destroy = new EventEmitter<ComponentRef<T>>();

  private componentRef: ComponentRef<T>;

  constructor(
    private viewContainerRef: ViewContainerRef,
    private resolver: ComponentFactoryResolver,
    private elRef: ElementRef,
    private globalInjector: Injector
  ) {
    this.injector = globalInjector;
  }

  ngAfterViewInit() {
    const injector = this.injector || this.globalInjector;
    const factory = this.resolver.resolveComponentFactory(this.component);
    this.componentRef = this.viewContainerRef.createComponent(factory, 0, injector);

    this.elRef.nativeElement.appendChild(this.componentRef.location.nativeElement);
    this.create?.emit(this.componentRef);
  }

  ngOnDestroy(): void {
    this.destroy?.emit(this.componentRef);
  }
}

And here's the usage:这是用法:

<div myComponentOutlet
           [component]="inner.component"
           [injector]="inner.injector"
           (create)="componentCreated($event)"></div>

Adjust it to your own needs根据自己的需要调整

It's not as robust as <div *ngComponentOutlet="myComponent; inputs:[...]; outputs:[...]"></div> , but it's something and it's quite clean and it works.它不像<div *ngComponentOutlet="myComponent; inputs:[...]; outputs:[...]"></div>那样健壮,但它确实不错,而且非常干净而且可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM