Select is not initialized with default value

Asked

Viewed 342 times

2

I created a component that has a type field <select> and receives a property [modelo] as input: if the template is null, the form is initialized empty; if it has content, it is initialized for modification.

HTML:

<form [formGroup]="modeloForm" (ngSubmit)="ngSubmit(modeloForm.value)">
  <input type="text" formControlName="name" id="name" placeholder="Nome"/>
  <label for="name">Nome</label>

  <select formControlName="item_id" id="item_id">
    <option [ngValue]="null" disabled selected>Escolha o banco:</option>
    <option *ngFor="let item of itens" [ngValue]="item.id">{{ item.name }}</option>
  </select>
  <button id="submit-btn" type="submit">
    Cadastrar
  </button>
</form>

Typescript:

itens: Item = ITENS; // array de itens importados de classe à parte
modeloForm: FormGroup;
_modelo: Modelo | null = null;

@Input() set modelo(modelo: Modelo | null){
  this._modelo = modelo;

  // tentei setar usando com a sintaxe do JavaScript, mas sem sucesso
  document.getElementById("item_id").nodeValue = !!this._modelo ? this._modelo.item_id + '' : '';

  // função que serve para resetar o formulário
  setTimeout(() => {
    this.modeloForm.reset({
      name: !!this._modelo ? this._modelo.name : '',
      item_id: !!this._modelo ? this._modelo.item_id : ''
    });
  }, 100);
}

Models:

interface Modelo{
  id: number;
  name: string;
  item_id: number;
}

interface Item{
  id: number;
  name: string;
}

const ITENS: Item[] = [
  {id:1, name:'item1'},
  {id:2, name:'item2'},
  {id:3, name:'item3'},
  {id:4, name:'item4'},
  {id:5, name:'item5'}
];

However, although initializing the form with the name and object correctly, the item selected in the field <select> does not appear until the field is selected. How should I proceed?

I tried to put the boot on ngInit() (even though it wouldn’t work because the ngInit is only called when the component is initialized for the first time), reverse the order between the definition by nodeValue and the fur modeloForm, comment the line I try to set manually by nodeValue, comment on the lines I try to set by modeloForm.reset and remove that part of setTimeout, all without success.

  • the values of the vector itens are passed at component initialization, as well as the values of modelo are passed through an inbound Property. I just gave a *ngFor in the elements of this array, just as I used the data of modelo to fill out the form. My question is more about the property value of select, which, when setting a default value, remains visually empty when initializing the component (if I selected the value 3, for example, the option that will appear empty when I view the form, even if modelo is defined)

  • I don’t know if I could be clear, but basically in the property component modelo is set correctly, and when I submit the property item_id of the object modelo is defined, but when I open the form, the field <select> is blank, as if the property item.name is equal to an empty string ("").

  • 1

    I didn’t see anything wrong, the *ngFor was supposed to be working, tried to change the [ngValue] for [value]?

  • I tried. It didn’t work, the value keeps appearing only when the field is selected.

  • 1

    I don’t know if yours ngSubmit there in your machine is wrong, but, here is missing the (. Do the following inside the ngOnInit() puts a.log console(items) to see what it shows.

  • (5) [{…}, {…}, {…}, {…}, {…}]&#xA;0: {id: 1, name: "item1"}&#xA;1: {id: 2, name: "item2"}&#xA;2: {id: 3, name: "item3"}&#xA;3: {id: 4, name: "item4"}&#xA;4: {id: 5, name: "item5"}&#xA;length: 5&#xA;__proto__: Array(0)

  • 1

    The only thing I think it might be there is the setTimeout() on the set of model, probably should be resetting the select, is the only thing I see for the problem.

  • I replaced the function code set by implementing the interface OnChanges, which has a function (ngOnChanges) call whenever an inbound Property is called, which slightly improved readability but did not solve the problem.

  • 1

    @Arthursiqueira I don’t know if I understand very well but initially your combo can come with no selected value and this is working perfectly. If the value is defined in the template item_id you would like to select the item in the combo, it would be this?

  • @Marcelovismari exactly that

Show 5 more comments

1 answer

1


Arthur, from what I understand, when the field item_id of your template being populated means that an item must be selected by default in your combo. If so, bind [value] in your select. See a example:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  itens = [
    { id: 1, name: 'item1' },
    { id: 2, name: 'item2' },
    { id: 3, name: 'item3' },
    { id: 4, name: 'item4' },
    { id: 5, name: 'item5' }
  ];

  modelo = {
    item_id: 5
  };
}

Template:

<select [value]="modelo.item_id">
  <option disabled>Escolha o banco:</option>
  <option *ngFor="let item of itens" [value]="item.id">{{ item.name }}</option>
</select>

If the item_id is completed, when loading the component your combo will have selected the same id item.

  • The big problem is that I get this data from the parent component, and when I open the child the option is only selected by clicking on the field select

  • 1

    @Arthursiqueira see if it is more or less this scenario: https://stackblitz.com/edit/angular-faaiys

  • More like: https://stackblitz.com/edit/angular-gaqb9z

  • 1

    @Arthursiqueira I modified your example a little, see if it fits you: https://stackblitz.com/edit/angular-9apubp

Browser other questions tagged

You are not signed in. Login or sign up in order to post.