Search code examples
angulartypescriptforeachangular-ngmodel

set input value based on selected dropdown value


Using [(ngModel)], I want to set an inputs value based on a selected dropdown.

I have managed to bind a selected dropdown onto an input field but I can't bind it if the selected dropdown value is an array. I need to bind multiple array properties to multiple input fields.

Here is a stackblitz I created and what I have tried so far.

TypeScript file:

savedCards = [];
selectedCard = '';

selectDropdownCard(card) {
  this.savedCards.find((item) => item.id === card.id)
    ? this.savedCards = this.savedCards.filter((item) => item.id === card.id)
    : this.savedCards = [card];
  this.assignToNgModel();
}

assignToNgModel() {
  this.selectedCard = '';
  this.savedCards.map((item) => this.selectedCard += item.viewValue + ' ');
  this.savedCards.forEach((item) => {
    console.log(item);
  });
  console.log(this.selectedCard);
}

HTML file:

<div class="div1" (click)="selectSavedCard()" [(ngModel)]="selectedCard" ngDefaultControl>
  <div *ngIf='!hasSelected'>
    <div>
      <p>dropdown</p>
    </div>
  </div>
  <div *ngFor="let card of savedCards">
    <div>
      <p>{{card.viewValue}}</p>
    </div>
  </div>
</div>

<div class="div2" *ngIf="show">
  <div *ngFor="let card of savedCreditCards" (click)="selectDropdownCard(card)">
    <div>
      <p>{{card.viewValue}}</p>
    </div>
  </div>
</div>

<input placeholder="id" [(ngModel)]="selectedCard" type="text">
<input placeholder="viewValue" [(ngModel)]="selectedCard" type="text">
<input placeholder="name" [(ngModel)]="selectedCard" type="text">
<input placeholder="value" [(ngModel)]="selectedCard" type="text">

I could use some guidance and suggestions on how to solve this.


Solution

  • Here's the forked stackblitz https://stackblitz.com/edit/angular-vpvjff with the solution I described in the comment. I think you should refactor you code as I'm not sure what's it doing.