I'm trying to print a specific object value based on a parameter that a user is giving.
So let's say that I've got the following object:
rateCardSelected: any = {
"carrierId": null,
"carrierName": null,
"customsClearanceCosts": null,
"flegtSurcharge": null,
"hsCodeCharge": null,
"provisionForPrePaidDutiesFactor": null,
"prepaidCustomsDuty": null,
"deliveryOrder": null,
"inspectionCharges": null,
"lsps20feet": null,
"lsps40feet": null,
"lastmileCtvrede": null,
"ocmFee": null
};
I fill this Object by using the a request:
getCarrierCosts(selectedCarrier: any){
let pathVariable = selectedCarrier;
let url = 'http://localhost:8080//shipmentRate/' + pathVariable;
let rateCardSelected = this.http.get(url)
rateCardSelected.subscribe((data) => this.rateCardSelected = data);
}
So for so good. If I console.log(this.rateCardSelected.carrierName);
it will gave me the carrier name as expected.
But my goal is that the user inputs what he wants to see. So I use this object to make the user select which value of the rateCardSelected
object needs to be printed:
nameDefinitions: any = [
{id: 'customsClearanceCosts', name: 'Customs clearance costs'},
{id: 'flegtSurcharge', name: 'Flegt surcharge'},
{id: 'hsCodeCharge', name: 'HS-code surcharge'},
{id: 'provisionForPrePaidDutiesFactor', name: 'Provision pre-paid duties'},
etc...
]
When the user selects one of the above I can also make the selected value visible with the following:
<mat-form-field floatLabel="never" appearance="outline">
<mat-label>Ledger</mat-label>
<mat-select [(value)]="selectedLedger" (selectionChange)="getLedger(selectedLedger)">
<mat-option matInput required placeholder="label" *ngFor="let ledger of nameDefinitions" [value]="ledger.id">
{{ledger.name}}</mat-option>
</mat-select>
</mat-form-field>
getLedger(selectedLedger: any){
console.log(selectedLedger);
}
This will print flegtSurcharge for example.
Now the part where I struggle:
How can I make sure that it will print the value of flegtSurcharge from the selectedRateCard? I've tried several things like:
getLedger(selectedLedger: any){
console.log(this.rateCardSelected.carrierName);
console.log(selectedLedger);
console.log(this.rateCardSelected.selectedLedger); //I want the value of the object right here!
}
But with no success, instead "undefined" is printed.
Edit:
After I changed console.log(this.rateCardSelected.selectedLedger);
to console.log(this.rateCardSelected[selectedLedger]);
it still prints undefined.
After reading Dynamically access object property using variable from what I understand you should be able to use a dot notation as well right? Or is this different in Angular?
Any tips regarding my code are very welcome since I'm new to Angular.