When i use viewContainerRef.createComponent, the dynamic component not load ngOninit! my…
- User
When i use
viewContainerRef.createComponent, the dynamic component not load ngOninit! my code: import { ChangeDetectorRef, Component, ComponentRef, ElementRef, ViewChild, ViewContainerRef } from '@angular/core'; import { EmojiServiceService } from './emoji-service.service'; import { EmojiComponent } from './emoji/emoji.component';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'myQuery'; @ViewChild('emojiInput') emojiInput: ElementRef; emojiComponentRef: ComponentRef;
constructor( private es: EmojiServiceService, private viewContainerRef: ViewContainerRef ) { }
addEmoji(event: any) { const emojiInput = this.emojiInput.nativeElement; const selection = window.getSelection(); const emojiInputRange = document.createRange(); emojiInputRange.selectNodeContents(emojiInput); this.emojiComponentRef = this.viewContainerRef.createComponent(EmojiComponent); this.emojiComponentRef.instance.id = event.id; this.emojiComponentRef.instance.size = '24px'; const emojiNode = this.emojiComponentRef.location.nativeElement; if (selection && selection.focusNode && emojiInputRange.isPointInRange(selection.focusNode, selection.focusOffset)) { const range = selection.getRangeAt(0);
codeif (selection.isCollapsed) { // Insert the emoji at the cursor position range.insertNode(emojiNode); range.collapse(false); } else { // Replace the selected text with the emoji range.deleteContents(); range.insertNode(emojiNode); } // Move the cursor to the end of the inserted emoji range.setStartAfter(emojiNode); range.collapse(true); // Update the selection and focus the emoji input selection.removeAllRanges(); selection.addRange(range); emojiInput.focus(); }} }
- Assistant
It seems like you are creating an instance of the EmojiComponent and inserting it into the DOM properly. However, the ngOnInit() of the dynamic component may not be called automatically in this case.
To call the ngOnInit() method of the dynamic component, you can do the following:
- Import OnInit in your AppComponent:
javascriptimport { OnInit } from '@angular/core';- Implement OnInit in the EmojiComponent class:
javascriptexport class EmojiComponent implements OnInit { // Your existing code here... ngOnInit(): void { console.log('EmojiComponent ngOnInit called'); // Add the code you want to execute on initialization here } }- In your AppComponent, call the ngOnInit method of the EmojiComponent instance after creating it: