Search code examples
javascriptangulartypescriptangular11

Angular nested object binding not working inside button onclick


<button (click)=updateDetails(app.id, app.extension.applicationId)>
      click this button
</button>
<br/>
<span>{{ app.extension.applicationId }}</span>

If I remove the HTML button element from my angular component code, the application seems to be correctly printing the value of the app.extension.applicationId. But if I add the HTML button element code then I see the below error during compilation,

Argument of type 'extension' is not assignable to the parameter of type 'string'

I am using nested objects in my application view.

More details below

The Rest service response that I am consuming

{
  "id": 86,
  "parentId": 65,
  "parentApplication": "Digital Tools",
  "extension": {
    "applicationId": 89,
    "applicationName": "ChatBot",
    "applicationRegion": "NA",
  }
}

updateDetails method signature

updateDetails(id: number, applicationId: string)

interfaces I have created

interface Extension {
    applicationId: string;
    applicationName: string;
    applicationRegion: string;
}

export interface Application {
    id: number;
    parentId: string;
    parentApplication: string;
    extension: {
        [key: string]: Extension;
    };
}

The application prints all the JSON response property values correctly and only the property app.extension.applicationId when used inside the Angular click function throws an error. But if I were to pass app.parentApplication as the argument the function seems to be compiling fine. I believe the issue has got to do with the nesting.


Solution

  • It is because your app.extension.applicationId is considered as an Extension.

    When I see the response you get from your service, I assume that interface Application is wrong. I think you wanted to write this:

    export interface Application {
        id: number;
        parentId: string;
        parentApplication: string;
        extension: Extension; // <- this
    }
    

    You also forgot the quotes around updateDetails in your html code:

    <button (click)="updateDetails(app.id, app.extension.applicationId)">
          click this button
    </button>