1

我正在使用一个组件工厂通过一个Block输入来加载不同的组件,该输入说明了块的特征 - 内部变量。然后,根据设置的变量,工厂将加载不同的组件。

这是我的工厂代码

import { Directive, Input, AfterContentInit, ComponentFactoryResolver, ViewChild, ViewContainerRef, Component } from '@angular/core';

import { GreenBlock } from './Blocks/GreenBlock';
import { BlueBlock } from './Blocks/BlueBlock';
import { YellowBlock } from './Blocks/YellowBlock';
import { Block } from './Block';


@Component({
  selector: 'block-factory',
  template: '<div #container></div>',
})
export class BlockFactory implements AfterContentInit  {

  @Input() block: Block;

  @ViewChild('container', {read: ViewContainerRef}) container;

  constructor(public resolver: ComponentFactoryResolver) 
  { 

  }

  ngAfterContentInit() {

    var content;

    switch(this.block.Type) 
    {
      case "yellow":
        content = this.resolver.resolveComponentFactory(YellowBlock);
      break;

      case "blue":
        content = this.resolver.resolveComponentFactory(BlueBlock);
      break;

      case "green":
        content = this.resolver.resolveComponentFactory(GreenBlock);
      break;

      default:
        content = this.resolver.resolveComponentFactory(YellowBlock);
      break;
    }

    let componentRef = this.container.createComponent(content);
    componentRef.instance.block = this.block;
  }
}

然后,为了通过 HTML 调用这个工厂,我使用以下符号:

<block-factory (ngModel)="newBlock" [block]="newBlock" style="margin:10px 5px;" ></block-factory>

对应于块(保存与块相关的一些信息的newBlock类),因此取决于屏幕上的块的设置,看起来会有很大不同。

现在,这newBlock取决于人们从下拉框中选择的内容。请参阅以下功能:

// Set the new block via what is clicked in the dropdown box
setNewBlock(block) 
{
  this.newBlock = block;
}

一个相当简单的功能。现在,正如预期的那样,newBlock 不会更新它的新“外观”,因为如果它们不是静态组件,Angular 就无法确定任何绑定。我的问题是 - 我怎样才能使 Angulars 绑定功能?

4

0 回答 0