Kenzo
Kenzo

Reputation: 377

Push object from search using Angular 2 into array

I created this search function that hits an API and generates results. I am now trying to push my found result on click to an array. How do I link a particular selection to my ngModel?

My old way was manual text:

<input type="text" class="form-control" placeholder="Angular" [(ngModel)]="company.technology[i].stack" name="technology_{{i}}" #technology="ngModel" required>

function to push:

onAddStack() {
   this.company.technology.push({stack: ''});
}

My new search feature:

 <input (keyup)="$event.target.value && searchTerm$.next($event.target.value)">
    <ul *ngIf="results">
     <a *ngFor="let result of results | slice:0:7" class="other" (click)="onAddStack()">
    <li>{{ result.name }}</li>
    </a>
 </ul>

Upvotes: 0

Views: 81

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68665

Pass the result into the click event handler

<a *ngFor="let result of results | slice:0:7" class="other" (click)="onAddStack(result)">
   <li>{{ result.name }}</li>
</a>

and in the handler push the passed parameter into the array

onAddStack(result) {
   this.company.technology.push(result);
}

Upvotes: 1

Related Questions