问题描述
所以我正在使用下面的代码通过ComponentFactoryResolver创建组件的新实例,下面是文件#1是我动态生成的组件,而#2是我从中生成它的组件
**#1 dynamic-spawned-component.component.ts **
@Component({
selector: 'dynamically-spawned-component',template: '
<p> The number passed in is {{ myNumber }},but this number will be updated dynamically as well ... </p>
'
})
export class DynamicallySpawnedComponent implements OnInit {
@input() myNumber : number;
constructor() { }
}
**#2 parent.component.ts **
import { DynamicallySpawnedComponent } from '../dynamically-spawned-component.component';
@Component({
selector: 'parent',template: '
<div #container></div>
<button (click)="addComponent">Add another component</button>
'
})
export class ParentComponent implements OnInit {
// The view child to spawn these new components
@ViewChild('container',{ read: ViewContainerRef }) container: ViewContainerRef;
// The reference to the newly spawned component
componentRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
ngOnInit(): void {
}
addComponent() {
// Create the resolver
const componentFactory : ComponentFactory<DynamicallySpawnedComponent > = this.componentFactoryResolver.resolveComponentFactory(DynamicallySpawnedComponent );
// Create a new instance of the dynamically spawned component
this.componentRef = this.container.createComponent(componentFactory)
// Assign a value to the myNumber variable inside of this newly created component
this.componentRef.instance.myNumber = 5;
}
}
因此,上面的代码可以正常工作,但例如,我单击添加3次并添加3个新生成的组件,我将如何访问这些新生成的组件并更改任何实例上的实例值myNumber变量中的3个?
如果我按了3次addComponent按钮,则预期的html应该看起来像这样:
The number passed in is 5,but this number will be updated dynamically as well
The number passed in is 5,but this number will be updated dynamically as well
<!-- THIS IS A BUTTON --> Add another component
解决方法
在parent.component.ts中
有一个(单击)事件,但是您没有调用函数“ addComponent()”
而不是将<button (click)="addComponent">
更改为<button (click)="addComponent()">