I have a form which contains 1 drop-down list and 2 inputs. I have a drop down list which contains several objects. When I select one of them, I can retrieve the whole object and I am supposed to filled the two other inputs with the value from the selected object. However, it seems there is an offset when I do that.
For instance I have an object banana in my list. If i select it nothing will happen.
The 2 other inputs will not be filled at first. Then if I select another object such as apple, the banana values will be retrieved and so on if I select Orange, Apple's values will be retrieved.
In my HTML file I have this :
<mat-form-field>
<mat-select placeholder="Code List"
(ngModel)]="contextScheme.codeListId"
(selectionChange)="completeInputAgencyAndVersion($event)">
<mat-option *ngFor="let codeList of codeLists"
[value]="codeList.codeListId">
{{codeList.codeListName}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Scheme ID</mat-label>
<input matInput required
[(ngModel)]="contextScheme.schemeId" [maxlength]="45"/>
</mat-form-field>
<mat-form-field>
<mat-label>Agency ID</mat-label>
<input matInput required
[(ngModel)]="contextScheme.schemeAgencyId" [maxlength]="45"/>
</mat-form-field>
Basically I only display everything and in the ts file I have the method completeInput :
completeInputAgencyAndVersion(event: MatSelectChange) {
this.service.getCodeList(event.value).subscribe(val => {
this.currCodeList = val; } );
if (this.currCodeList) {
this.contextScheme.schemeAgencyId =
this.currCodeList.agencyId.toString();
this.contextScheme.schemeVersionId =
this.currCodeList.versionId.toString();
this.contextScheme.ctxSchemeValues =
this.convertCodeListValuesIntoContextSchemeValues(
this.currCodeList.codeListValues);
this.dataSource.data = this.contextScheme.ctxSchemeValues;
}
}
My question is why is there this offset and how can I fix it ?
Thanks !
EDIT : Whenever I chose an object from my drop-down list, I can see that the correct request is sent and that I receive the correct piece of information, the issue dwells in Angular and how it load the information.
Your issue is related to Angular Change Detection which is not happening once you get your async data. You can notify angular check for change once response had come from server.
constructor(private cd: ChangeDetectorRef) {
}
completeInputAgencyAndVersion(event: MatSelectChange) {
this.service.getCodeList(event.value).subscribe(val => {
this.currCodeList = val;
if (this.currCodeList) {
this.contextScheme.schemeAgencyId =
this.currCodeList.agencyId.toString();
this.contextScheme.schemeVersionId =
this.currCodeList.versionId.toString();
this.contextScheme.ctxSchemeValues =
this.convertCodeListValuesIntoContextSchemeValues(
this.currCodeList.codeListValues);
this.dataSource.data = this.contextScheme.ctxSchemeValues;
this.cd.detectChanges();
}
} );
}
来源:https://stackoverflow.com/questions/53195397/offset-selectionchange-angular