Skip to content
Advertisement

Angular-6 show and hide drop-down select option not showing proper data

I have 2 types of drop-down based on the select value column drop-down will show.

(one for to show database data, another one for to show desktop data.)

https://stackblitz.com/edit/angular-ivy-3n238j?file=src%2Fapp%2Fapp.component.html

app.componet.html

<!-- show database data -->
<select *ngIf="isdbShow" [(ngModel)]="dynamicArray[i].title2" class="form-control">
    <option *ngFor="let data of dynamicArray[i].dropdownData;">{{data}}</option>
</select>

<!-- show desktop data -->
<select *ngIf="isdesktopShow" [(ngModel)]="dynamicArray[i].title2" class="form-control">
    <option *ngFor="let data of dynamicArray[i].dropdownData;">{{data.name}}</option>
</select>

My issue is below

  1. In 1st row if I select desktop it will show desktop data’s in value column drop-down.
  2. In 2nd row if I select database, desktop will be showed as [object object] check bellow image

enter image description here

app.component.ts

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

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  dynamicArray: Array<any> = [];
  newDynamic: any = {};
  dbValue = ["mysql", "oracle", "mongo"];
  desktopValue = [{'id':'1', 'name':'dell'}, {'id':'2', 'name':'lenovo'}, {'id':'3', 'name':'hp'}];
  isdbShow:boolean = false;
  isdesktopShow:boolean = false;
  ngOnInit(): void {
    this.newDynamic = { title1: "", title2: "", dropdownData: [] };
    this.dynamicArray.push(this.newDynamic);
  }
  addRow(index) {
    this.newDynamic = { title1: "", title2: "", dropdownData: [] };
    this.dynamicArray.push(this.newDynamic);
    console.log(this.dynamicArray);
    return true;
  }

  deleteRow(index) {
    if (this.dynamicArray.length == 1) {
      return false;
    } else {
      this.dynamicArray.splice(index, 1);
      return true;
    }
  }

  changed(value, index) {
    let dropdownData;
    if (value == 1) {
      this.isdbShow = true;
      this.isdesktopShow = false;
      this.dynamicArray[index].dropdownData = this.dbValue;
    }

    if (value == 2) {
      this.isdbShow = false;
      this.isdesktopShow = true;
      this.dynamicArray[index].dropdownData = this.desktopValue;
    }
  }
}

Please check the flow in my demo link with same scenario. 1st row select desktop and 2nd row database

Advertisement

Answer

Try this

<select *ngIf="isdbShow" [(ngModel)]="dynamicArray[i].title2" class="form-control">
                <option *ngFor="let data of dynamicArray[i].dropdownData;">{{data?.name ? data?.name : data}}</option>
              </select>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement