0

Im doing a form that changes with selected option.

<select multiple class="form-control col-6" id="efeitos" [(ngModel)]="test" name='effect'>
                <option *ngFor='let eff of effects' [ngValue]="eff">{{eff.name}}</option>
            </select>
            <textarea class="col-5" readonly>{{test.desc}}</textarea>

textarea never appears.

<p>{{test | json}}</p>

Shows: [ { "name": "effect", "desc": "Lorem ipsum dolor" } ] instead of desired { "name": "effect", "desc": "Lorem ipsum dolor" }

first post here, pls some help

3 Answers3

0

You get the array in test because you use the multiple attribute, just remove multiple (if you need the multiple, then Array, I think, is the expected result for you)

izmaylovdev
  • 1,828
  • 8
  • 16
0

it could be also this way: {{

{{test[0] | json}}

}}
0

When the property multiple is supplied to the select tag, there could be multiple selections. So naturally the test variable would be an array. You could try to gather desc properties from all the selected elements using array map function.

Controller

export class AppComponent  {
  ...
  test: Effect[] = [{ 'name': '', 'desc': 'please select an effect'}];

  getDesc() {
    return this.test.map(item => item.desc)
  }
}

Template

<textarea class="col-5" readonly>
{{ getDesc() }}
</textarea>

Note: This method is inefficient. If you aren't controlling the change detection strategy manually, getDesc() function might be called multiple times than intended. This will be a bottleneck when the test array has too many elements since the entire array is iterated for each call.

ruth
  • 29,535
  • 4
  • 30
  • 57