[英]How to bind and change dynamic component input in angular?
I have a dynamic component an app component.我有一个动态组件一个应用程序组件。 I am dynamically compile the dynamic component and add to app component.
我正在动态编译动态组件并添加到应用程序组件。
@Component({
selector: 'app-dynamic',
template: `<p>Dynamic Component {{ index }}</p>`
})
export class DynamicComponent {
@Input() index: number;
}
And app component:和应用程序组件:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
counter = 1;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
ngOnInit(){
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
const componentRef = this.container.createComponent(componentFactory);
componentRef.instance.index = this.counter++;
}
add(){
this.counter++;
}
}
But after start the applicaiton, I am increasing the counter
.但是在启动应用程序后,我正在增加
counter
。 But it does not change in dynamic component.但它不会在动态组件中改变。 Why?
为什么?
I think you can't pass a counter by reference so you can do :我认为你不能通过引用传递一个计数器,所以你可以这样做:
export class AppComponent implements OnInit {
name = 'Angular';
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
counter = 1;
componentRef: DynamicComponent;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
ngOnInit(){
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
this.componentRef = this.container.createComponent(componentFactory);
this.componentRef.instance.index = this.counter++;
}
add(){
this.componentRef.instance.index = this.counter++;
}
}
Maybe this can work if you can tell me ;)如果你能告诉我,也许这可以工作;)
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
counter = 1;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
ngOnInit(){
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
const componentRef = this.container.createComponent(componentFactory);
componentRef.instance.index = this.counter;
}
add(){
this.counter++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.