Angular动态组件的变化检测可能不会按预期工作的常见原因是,动态组件的输入属性没有正确绑定。以下是一个解决方法的示例代码:
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { DynamicComponent } from './dynamic.component';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
loadDynamicComponent() {
this.container.clear();
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
const componentRef = this.container.createComponent(componentFactory);
componentRef.instance.inputData = 'Hello Angular!';
}
}
OnChanges
生命周期钩子来检测输入属性的变化:import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-dynamic',
template: `
{{ inputData }}
`
})
export class DynamicComponent implements OnChanges {
@Input() inputData: string;
ngOnChanges(changes: SimpleChanges) {
if (changes.inputData) {
console.log('Input data changed:', changes.inputData.currentValue);
}
}
}
loadDynamicComponent
方法来动态加载组件:
在这个示例中,每当inputData
属性的值发生变化时,动态组件中的ngOnChanges
方法将被调用,并打印出新的属性值。这样可以确保动态组件的变化检测正常工作。
下一篇:Angular动态组件属性绑定