In my form, I have the following section:
<div formArrayName="studentPublishing" *ngFor="let all of getstudentPublishing().controls; index as i">
<div class="form-group data">
<input type="text" list="options" class="form-control" placeholder="Students" (change)="getAuthor($event,i)" [formControlName]="i" required>
<datalist id="options">
<option *ngFor="let c of dataStudent" [value]="c.name">{{ c.name }}</option>
</datalist>
<div class="rem"><button (click)="removeAuthor(i)">-</button></div>
<div *ngIf="!formPublic.get('studentPublishing')?.valid && formPublic.get('studentPublishing')?.touched" class="validation-error">
<p>Authors are mandatory</p>
</div>
</div>
</div>
<div id="add" class="add"><button type="button" (click)="addAuthor()">Author +</button></div>
Everything is functioning correctly. The value displayed in the input is the Student object retrieved from the database. However, when a student is selected, it only shows [object Object].
Below is my TypeScript function that receives the value from the datalist and assigns it to the "student" array variable in the form:
getAuthor(e: any, id:number){
const studentName = e.target.value;
const studentSelected = this.dataStudent.find(x => x.name === studentName);
if (studentSelected) {
this.getstudentPublishing().at(id).setValue(studentSelected);
}
}
I tried using ngValue and also attempted to stringify the value using the json pipe:
<option *ngFor="let c of dataStudent" [ngValue]="c">{{ c.name | json }}</option>
I even tried passing the value as a string with just the name of the selected object:
<option *ngFor="let c of dataStudent" value="{{ c.name }}"></option>
However, when saving the value in the variable, only the name is stored instead of the entire object.
Here is how the input appears when a student is selected:
input datalist image showing [object Object]
This is the desired appearance after selecting a student:
input datalist image displaying selected student's name
Solution
Thanks to Daniel Gimenez's helpful response, I managed to resolve the issue. The solution looked like this:
this.formPublic.updateValueAndValidity();
if(this.formPublic.valid){
const studentControls = this.getstudentPublishing().controls;
const students = studentControls.map(y => {
const name = y.value;
console.log(name);
return this.dataStudent.find(student => student.name === name);
});
for (let i = 0; i < students.length; i++) {
this.getstudentPublishing().at(i).setValue(students[i]);
console.log(students[i]?.name);
}
}