0

am trying to create select option dynamically using Renderer2. at present am not able to create <Select></Select> element. but i can see able to see <options> are created. due to some concerns am not allowed to share all snippets. apologizes for that.

Issue is: as its not creating select element. its just simply showing first element of array. i could get all elements when i console it in ngOniti()

no other console errors as well.

PFA.

enter image description here

kindly someone help me on this and point me right direction. if possible pls share working demo. after spend so many hours i found this only .

    arr= ["AAA", "BBB", "CCC", "DDD", "EEE"];
    const select = this._rend.createElement('select');
  select.name = name;
  var option = this._rend.createElement('option');      
    this._rend.appendChild(select, option);
    this._rend.appendChild(option, document.createTextNode(''));
  
    arr.forEach( aaaa=>{ 
        option = this._rend.createElement('option');        
        this._rend.appendChild(option, document.createTextNode(aaaa));
        if (aaaa === value)
          option.selected = true;
            this._rend.appendChild(select, option);
        
    }) 

Note: kindly share any other better solutions if mine is not at all good one.

Thank you so much every one.

Community
  • 1
  • 1
Mr. Learner
  • 978
  • 2
  • 18
  • 48

1 Answers1

0

Please check this code for your reference on creating the select options in stackblitz

class AppComponent {
   arr = ["AAA", "BBB", "CCC", "DDD", "EEE"];
   value = 'BBB'

     constructor(private el: ElementRef, private renderer: Renderer2) {
       const select = renderer.createElement('select');
       select.name = name;
       var option = renderer.createElement('option');
       renderer.appendChild(select, option);
       renderer.appendChild(option, document.createTextNode(''));

       this.arr.forEach(aaaa => {
         option = renderer.createElement('option');
         renderer.appendChild(option, document.createTextNode(aaaa));
         if (aaaa === this.value) option.selected = true;
         renderer.appendChild(select, option);

       })
       renderer.appendChild(this.el.nativeElement, select);
     }
}

In this class I'm creating a select element with Renderer2
then appending the options element which is created with Renderer2 is appended to the select element

finally i'm appending the select element to the AppComponent nativeElement

Flow

 Created `select
 |
 V
 Appended `Option` to select
 |
 V
 Appended `select` to the AppComponent host element

https://stackblitz.com/edit/angular-wpstnh

Sheik Althaf
  • 1,595
  • 10
  • 16
  • @Sheik Althaf i accept your answer. but some how its getting failed in requirement . – Mr. Learner Mar 18 '19 at 10:53
  • @worstCoder My review vote based on the version of this answer that hadn't anything but a little sentence plus the link. – deHaar Mar 18 '19 at 11:11