我知道这不是最好的解决方案,但是我希望能够从JSON响应中动态加载组件,具体如下:

应用组件

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1> {{component.title}} {{component.selector}}',
    providers: [AppService],
    directives: [ExampleComponent]
})
export class AppComponent implements OnInit {

    component:{};

    constructor(
        private _appService: AppService) {
    }

    ngOnInit() {
        this.component = this._appService.getComponent();
    }
}

应用服务
@Injectable()
export class AppService {

    component = {
        title: 'Example component',
        selector: '<example></example>'
    }

    getComponent() {
        return this.component;
    }
}

example.component
@Component({
    selector: 'example',
    template: 'This a example component'
})
export class ExampleComponent  {
}

如果运行此示例,则输出为<example></example>,但实际上未呈现该组件。我也尝试过使用[innerHtml]="component.selector",但这也没有用。有人有想法或建议吗?

最佳答案

更新

用于创建组件的代码有所更改。
可以在Angular 2 dynamic tabs with user-click chosen components中找到一个工作示例



要动态插入组件,可以使用ViewContainerRef.createComponent()
对于声明式方法,您可以使用一个辅助组件,例如

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private resolver: ComponentResolver) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
   this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
      this.cmpRef = this.target.createComponent(factory)
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
  }
}

另请参阅Angular 2 dynamic tabs with user-click chosen components

在您的示例中,您可以像这样使用它

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1> {{component.title}} <dcl-wrapper [type]="component.type"></dcl-wrapper>',
    providers: [AppService],
    directives: [ExampleComponent]
})
export class AppComponent implements OnInit {

    component:{};

    constructor(
        private _appService: AppService) {
    }

    ngOnInit() {
        this.component = this._appService.getComponent();
    }
}

import {ExampleComponent} from './example.component.ts';

@Injectable()
export class AppService {

    component = {
        title: 'Example component',
        type: ExampleComponent
    }

    getComponent() {
        return this.component;
    }
}

关于angular - Angular2 : Loading components dynamically from a service response,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37540197/

10-12 06:11