Search code examples
javascriptangulartypescriptangular-template

Angular passing a dictionary into a change event


I am trying to pass a dictionary into a function like so:

<ng-template class="example-container" ngSwitchCase="twoTextFields">
      <mat-form-field appearance="outline">
          <mat-label>{{field.firstFieldName}}</mat-label>
          <input matInput (change)="onUpdate(field.db_name, {[field.first_db_name]: $event})">
      </mat-form-field>
      <mat-form-field appearance="outline">
          <mat-label>{{field.secondFieldName}}</mat-label>
          <input matInput (change)="onUpdate(field.db_name, {[field.second_db_name]: $event})">
      </mat-form-field>
</ng-template>

It gives me many syntax errors similar to this:

Parser Error: Missing expected ) at column 26 in [onUpdate(field.db_name, {[field.first_db_name]: $event})] in @14:43 ("         <mat-label>{{field.firstFieldName}}</mat-label>
          <input matInput (change)="[ERROR ->]onUpdate(field.db_name, {[field.first_db_name]: $event})">
      </mat-form-field>
      <mat-form-f"): @14:43

Is it possible to pass a dictionary as done above or not? If it is could I have some guidance on how it would be possible, otherwise it would also help to know if it is not possible! I am new to Angular so anything helps!

I'm trying to translate over some code I had from React and it would be much simpler if I didn't have to rewrite the change function. I also tried using ngModelChange and I receive the same error.

Thank you!


Solution

  • Unfortunately, this triggers a syntax error. The main reason for this is that "[]" is used as a special character(s) in angular directives / templates.

    You can do this instead:

    <mat-form-field appearance="outline">
        <mat-label>{{field.firstFieldName}}</mat-label>
        <input matInput (change)="onUpdate(field.db_name, convertToDict(field.first_db_name, $event))">
    </mat-form-field>
    <mat-form-field appearance="outline">
        <mat-label>{{field.secondFieldName}}</mat-label>
        <input matInput (change)="onUpdate(field.db_name, convertToDict(field.second_db_name, $event))">
    </mat-form-field>
    

    Then on your code behind, you can create the helper function like so (in your app.component.ts):

    export class AppComponent  {
      ... truncated code . ..
    
      convertToDict(key: any, value: any): any {
        return {[key]: value}
      }
    
      onUpdate(fieldName: string, eventDict: any) {
        console.log(fieldName);
        console.log(eventDict);
      }
    
      ... truncated code ...
    }
    

    This is a workaround if you still would want to have a dictionary of your data. We did it by using a simple helper / converter function.