Search code examples
angularformsdynamicdropdownrenderer

Angular 4 Dynamic Forms: Edit Dropdown NOT Working


I am creating an Angular 4 dynamic multi step form. The last step of the form shows the user all the values they have entered and gives them a chance to edit. When a user clicks "edit" it will take them back to that particular question.

Edit works with inputs and checkboxes, but does not work with dropdowns. It will focus on that element, but does not show the value the user originally selected.

I have include an example.

Is there something I have to do differently with dropdowns?

Thanks


Solution

  • You should avoid using this.renderer2.selectRootElement method because it clears content of your selected element:

    selectRootElement(selectorOrNode: string|any): any {
        let el: any = typeof selectorOrNode === 'string' ? 
                document.querySelector(selectorOrNode) :
                selectorOrNode;
        if (!el) {
          throw new Error(`The selector "${selectorOrNode}" did not match any elements`);
        }
        el.textContent = ''; <==================== this code
        return el;
    }
    

    https://github.com/angular/angular/blob/c8a1a14b87e5907458e8e87021e47f9796cb3257/packages/platform-browser/src/dom/dom_renderer.ts#L137-L145

    One option to handle autofocus is passing focusedKey to dynamic form:

    <dynamic-control [input]="control" [form]="form" [focusedKey]="focusedKey">
                                                       ^^^^^^^^^^^^^^^^^^^^^^^
    

    Then you can create autofocus directive like:

    @Directive({
      selector: '[autofocus]'
    })
    export class AutofocusDirective {
      constructor(private el: ElementRef) {}
    
      @Input() set autofocus(value) {
        if (value) {
          this.el.nativeElement.focus();
        }
      }
    }
    

    and use it instead of id and ChangeDetectorRef

    <select [autofocus]="focusedKey === input.key"
    

    Fixed Example