我正在使用组件工厂通过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
对应于Block(包含与块相关的一些信息的类),因此取决于屏幕上的块看起来会有多大不同。
现在,此newBlock
会根据用户从下拉框中选择的内容进行更改。请参阅以下功能:
// Set the new block via what is clicked in the dropdown box
setNewBlock(block)
{
this.newBlock = block;
}
一个相当简单的功能。现在,正如预期的那样,newBlock不会使用它的新“外观”进行更新,因为如果它们不是静态组件,Angular无法找出任何绑定。我的问题是 - 如何制作Angulars绑定功能?