Home > OS >  Renderer2.appendChild is not working as expected?
Renderer2.appendChild is not working as expected?

Time:06-27

in Angular component, I am trying to create a new input html element and insert in specific location of the template

the component code

@ViewChild('pickerLocation', { static: false }) pLocationSpan: ElementRef<HTMLSpanElement>;

constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document: Document) { }

ngOnInit(): void {
    const pickerInput = this.renderer.createElement('INPUT');
    const picker = new TempusDominus(pickerInput);
    this.renderer.appendChild(this.pLocationSpan.nativeElement, pickerInput);
  }

the template code

<div >
    <label for="datetimepickerInput">{{label}}</label>
    <span id="locationSpan" ngModel #pickerLocation></span>
    <span >
        <span ></span>
    </span>
</div>

however if I changed the line

this.renderer.appendChild(this.pLocationSpan.nativeElement, pickerInput);

to

this.renderer.appendChild(this.elementRef.nativeElement, pickerInput);

it works, however I need the input in specific location. so what could be the problem??

CodePudding user response:

@ViewChild query for elements is only possible in NgAfterViewInit() lifecycle the earliest. Because <span #pickerLocation> needs to be rendered first before it can be queried and accessed.

ngAfterViewInit(): void {
    const pickerInput = this.renderer.createElement('INPUT');
    const picker = new TempusDominus(pickerInput);
    this.renderer.appendChild(this.pLocationSpan.nativeElement, pickerInput);
  }
  • Related