Judson Terrell Judson Terrell - 2 months ago 12
TypeScript Question

Angular 2 ngModel where Id is something

I have an array of objects like so...

this.survey = [

{id: 1, answer: ""},
{id: 2, answer: ""},
{id: 3, answer: ""},
{id: 4, answer: ""},
{id: 5, answer: ""},
{id: 6, answer: ""},
{id: 7, answer: ""},
{id: 8, answer: ""},
{id: 9, answer: ""},
{id: 10, answer: ""},
{id: 11, answer: ""},
{id: 12, answer: ""},
{id: 13, answer: ""},
{id: 14, answer: ""},
{id: 15, answer: ""},
{id: 16, answer: ""},
{id: 17, answer: ""},
{id: 18, answer: ""},
{id: 19, answer: ""},
{id: 100, answer: ""},
{id: 101, answer: ""}

];


How can I bind to the object where value of id = 101 for the following text area?

<textarea name="comments" class="form-control" (change)="updateSurvey($event, 101)"
[(ngModel)]="survey.?????"></textarea>


I know that normally it could be done by knowing the index position easlily but I cannot always rely on that so how can I bind to where id = 101 in this case? as opposed to [(ngModel)]="survey[21]"

Thanks

Answer

I assume its not possible without using the index.

Possible way to go:

<textarea name="comments" class="form-control" (change)="updateSurvey($event, 101)" 
[value]="getSurveyAnswer(101)"></textarea>

in your component:

getSurveyAnswer(id: number): string {
   return this.survey.find(s => s.id == id);
}
Comments