Angular 4如何使用NgComponentOutlet

时间:2017-04-02 18:28:09

标签: angular angular4

我讲了这个类似的问题。 angular 4+ assign @Input for ngComponentOutlet dynamically created component

但是已经有一个月了。有什么变化吗?

基本上,我遵循了本指南并创建了一个动态组件:https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

通过这种方法,我可以为动态组件分配一个值: (<AdComponent>componentRef.instance).data = adItem.data;

是否仍然如此我无法使用开箱即用的NgComponentOutlet为动态组件赋值? (https://angular.io/docs/ts/latest/api/common/index/NgComponentOutlet-directive.html

2 个答案:

答案 0 :(得分:2)

您可以传入这样的自定义注射器 - https://github.com/angular/angular/issues/16373#issuecomment-306544456

这有点像黑客,所以我们最终使用了这个库 -

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

像魅力一样工作!

答案 1 :(得分:0)

就我而言,我在组件上使用ngBaseDef.inputs.data。

查看示例:


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

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() {
  }

}

祝您愉快 希望对您有帮助!