I have a problem in my Angular 6 application and really can't find answer right now so please help me if you can. Thank you. The problem is next:
I have an array (userDocuments) with this content:
[{"DocumentId":1,"DocumentName":"Osobna iskaznica","Mark":"13994000"},{"DocumentId":2,"DocumentName":"Putovnica","Mark":"qprtobm777"}].
Dropdown is being populated from this array. Beside dropdown is button which is used for editing selected element content in dialog box.
<select id="select-document" class="form-control" [(ngModel)]="selectedDocumentId">
<option *ngFor="let document of userDocuments" [value]="document.DocumentId">
{{ document.DocumentName }} ({{ document.Mark }})</option>
</select>
<button class="btn btn-danger btn-40 ml-1" type="button" (click)="openDocumentDailog(true)"> <i class="fa fa-edit"></i></button>
After component init when dropdown is being populated and hitting edit button dialog opens with data of selected array element. Everything works fine. Then I choose second value from dropdown and getting error about undefined element. Here is calling method for edit:
openDocumentDailog(edit: boolean) {
const currentDoc = this.userDocuments.find(x => x.DocumentId === this.selectedDocumentId);
console.log('array: ' + JSON.stringify(this.userDocuments));
console.log('DocumentId: ' + this.selectedDocumentId);
console.log(this.userDocuments.find(x => x.DocumentId === this.selectedDocumentId));
const dialogRef = this.dialog.open(NewDocumentComponent, {
width: '400px',
data: {
userId: this.loggedUser.id,
edit: edit,
docId: edit ? currentDoc.DocumentId : null,
docName: edit ? currentDoc.DocumentName : null,
docMark: edit ? currentDoc.Mark : null
}
});
...
For variable currentDoc I'm getting error that is undefined in second search. As you can see I'm logging values. Here are results:
array: [{"DocumentId":1,"DocumentName":"Osobna iskaznica","Mark":"13994000"},{"DocumentId":2,"DocumentName":"Putovnica","Mark":"qprtobm777"}]
DocumentId: 1
Object { DocumentId: 1, DocumentName: "Osobna iskaznica", Mark: "13994000" }
array: [{"DocumentId":1,"DocumentName":"Osobna iskaznica","Mark":"13994000"},{"DocumentId":2,"DocumentName":"Putovnica","Mark":"qprtobm777"}]
DocumentId: 2
undefined
In code to me everything looks correct because documentId value (1 or 2) is present in one of array elements. Also I need to say when I choose back first value from dropdown also getting an error message of undefined element. After first edit next edits are not working anymore because of array.find method.
Am I missing something or is problem somewhere deeper? Thank you.
Zeljko