3

我发现了这个类似的问题。angular 4+ 为 ngComponentOutlet 动态创建的组件分配 @Input

但是已经过去一个月了。有什么改变吗?

基本上,我按照本指南创建了一个动态组件: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

4

2 回答 2

2

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

这是一种 hack,所以我们最终使用了这个库——

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

像魅力一样工作!

于 2018-04-09T19:27:34.837 回答
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];
  }
}


示例组件

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

}

祝你今天过得愉快!希望能帮助到你!

于 2019-06-12T10:04:43.090 回答