वर्तमान में, मैं गतिशील रूप से एक घटक को लोड कर सकता हूं और इसे व्यूचाइल्ड में इस तरह प्रदर्शित कर सकता हूं:
@Component({
selector: '...',
template: '<ng-container #viewRef></ng-container>'
})
export class SomeComponent {
@ViewChild('viewRef', {read: ViewContainerRef}) public viewRef;
constructor(private compiler: Compiler) {}
ngAfterViewInit() {
this.compiler.compileModuleAndAllComponentsAsync(SomeModule).then((factory) => {
this.componentRef = this.placeholder.createComponent(factory);
});
}
}
अब मैं एकाधिक घटकों को लोड करना चाहता हूं और उन्हें एक सूची में गतिशील रूप से प्रदर्शित करना चाहता हूं। ViewChildren
इसका समाधान होना चाहिए। समस्या यह है, ViewChildren
ViewChild
पर नए तत्वों को जोड़ने या उन्हें createComponent
के समान बनाने की अनुमति नहीं देता है।
मैं गतिशील घटक कैसे बना सकता हूं और उन्हें ViewChildren
में कैसे जोड़ सकता हूं?
1 उत्तर
आप DOM से तत्वों या निर्देशों की QueryList प्राप्त करने के लिए ViewChildren का उपयोग कर सकते हैं। जब भी कोई चाइल्ड एलिमेंट जोड़ा जाता है, हटाया जाता है या स्थानांतरित किया जाता है, तो क्वेरी सूची अपडेट की जाएगी, और क्वेरी सूची में देखे जा सकने वाले परिवर्तन एक नया मान उत्सर्जित करेंगे। इसका मतलब है कि आप अपने viewRefs.changes
ईवेंट पर सब्सक्रिप्शन बना सकते हैं और ComponentFactoryResolver का उपयोग करके गतिशील रूप से घटकों को लोड कर सकते हैं। . नीचे दिया गया उदाहरण देखें:
export class SomeComponent {
@ViewChildren('viewRef', {read: ViewContainerRef})
public viewRefs: QueryList<ViewContainerRef>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
ngAfterViewInit() {
this.viewRefs.changes.subscribe((list: QueryList<ViewContainerRef>) => {
list.forEach((viewRef: ViewContainerRef, index: number) => {
const componentFactory: ComponentFactory<any> = this.componentFactoryResolver.resolveComponentFactory(OtherComponent);
viewRef.createComponent(componentFactory, index);
});
});
}
}
संबंधित सवाल
नए सवाल
angular
Google से वेब फ्रेमवर्क के बारे में प्रश्न इस टैग का उपयोग कोणीय प्रश्नों के लिए करें जो एक व्यक्तिगत संस्करण के लिए विशिष्ट नहीं हैं। पुराने AngularJS (1.x) वेब ढांचे के लिए, कोणीयज टैग का उपयोग करें।