Encountering an error of undefined upon submission of a form while utilizing ng

Sorry if this question has been asked before, but I've searched extensively online and still can't find a solution. I'm new to Angular and TypeScript and I may be overlooking something simple, but I can't get it to work. Any help would be appreciated. Here's the issue,

I have a modal popup window with two inputs in it. When I click on the Save button, using ngForm, I am unable to pass the values to the save method. Here is my code, could you please advise me on what I might be doing wrong here,

asset.component.html

<ng-template #content let-modal>
    <div class="modal-header row d-flex justify-content-between mx-1 mx-sm-3 mb-0 pb-0 border-0">
        <h3 class="modal-title" id="modal-basic-title">Add Asset</h3>
        <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
            <span aria-hidden="true"&litm;&times;</span>
        </button>
    </div>
    <div class="modal-body">
        <form #asset='ngForm' (ngSubmit)="saveAsset(asset.value)">
            <div class="form-group">
                <h4><label for="assetId" class="form-label text-right" style="margin: 10pt"><b>Asset Name</b></label></h4>
                <input id="assetId" name="assetId" class="form-control element-text" list="assetDatalistOptions"
                       (change)="getAssetValue()" placeholder="Enter Asset Name ... " ngModel>
                <datalist id="assetDatalistOptions">
                    <option *ngFor="let asset of assets" value="{{asset.data_dictionary_entry.text}}">
                        {{asset.data_dictionary_entry.id}}-{{asset.data_dictionary_entry.text}}
                    </option>
                </datalist>
            </div>

            <div class="form-group">
                <h4><label for="airText" style="margin: 10pt"><b>Asset Information Requirement</b></label></h4>
                <div class="input-group">
                    <input id="airText" name="airText" class="form-control element-text" placeholder="Enter AIR Text ... " ngModel>
                </div>

                <h4><label for="assetAirContent" style="margin: 10pt"><b>Linked AIR</b></label></h4>
                <div class="form=group" *ngFor="let asset of assets">
                    <ul *ngFor="let air of asset.airs" id="assetAirContent" class="list-group-horizontal-md">
                        <li *ngIf="asset.data_dictionary_entry.text === selectedAssetText &&  asset.airs.length>0" class="list-inline element-text">{{air}}</li>
                    </ul>
                </div>
            </div>
            <div class="modal-footer">
                <button data-dismiss="modal" class="btn btn-info btn-lg">Save</button>
                <button type="button" class="btn btn-danger btn-lg" (click)="modal.close('Cancel')">Cancel</button>
            </div>
        </form>
    </div>

</ng-template>

asset.component.ts

assets: Array<Asset> = [];
saveAsset(asset: Asset): void {
        console.log("Saving Asset : ",asset);
        this.assetService.save(asset)
            .subscribe(asset => this.assets.push(asset));
    }

asset.ts

export interface Asset {
    id: string;
    data_dictionary_entry: DataDictionaryEntry
    airs: string[];
}

I hope I've included all the pertinent code (I removed some in between to keep the question concise). One thing to note, inside asset.component.html, I'm trying to pass the values of input fields with IDs assetId and airText. Any assistance would be highly valued. Thank you, and I look forward to receiving some valuable advice.

EDIT:

The undefined value I receive can be seen in the image provided. I have updated the code to see what is being selected before I send it over, which can be viewed in the JSON I'm printing on the form page. Within saveAsset, I'm creating an alert to display asset.id on the screen. https://i.stack.imgur.com/fcP6C.png

Answer â„–1

By using a reproduced scenario (such as stackblitz), I could effectively troubleshoot the issue. My initial suspicion is that the

(ngSubmit)="saveAsset(asset.value)"
on the <form> element is not triggering. Is the saveAsset() function currently being called? Either way, I have made changes to trigger it when clicking the Save button.

 <div class="modal-header row d-flex justify-content-between mx-1 mx-sm-3 mb-0 pb-0 border-0">
        <h3 class="modal-title" id="modal-basic-title">Add Asset</h3>
        <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
            <span aria-hidden="true"&‌​gt;&times;</span>
        </button>
    </div>
    <div class="modal-body">
        <form #asset = 'ngForm'>
            <div class="form-group">
                <h4><label for="assetId" class="form-label text-right" style="margin: 10pt"><b>Asset Name</b></label></h4>
                <input id="assetId" name="assetId" class="form-control element-text" list="assetDatalistOptions"
                       (change)="getAssetValue()" placeholder="Enter Asset Name ... " ngModel>
                <datalist id="assetDatalistOptions">
                    <option *ngFor="let asset of assets" value="{{asset.data_dictionary_entry.text}}">
                        {{asset.data_dictionary_entry.id}}-{{asset.data_dictionary_entry.text}}
                    </option>
                </datalist>
            </div>

            <div class="form-group">
                <h4><label for="airText" style="margin: 10pt"><b>Asset Information Requirement</b></label></h4>
                <div class="input-group">
                    <input id="airText" name="airText" class="form-control element-text" placeholder="Enter AIR Text ... " ngModel>
                </div>

                <h4><label for="assetAirContent" style="margin: 10pt"><b>Linked AIR</b></label></h4>
                <div class="form=group" *ngFor="let asset of assets">
                    <ul *ngFor="let air of asset.airs" id="assetAirContent" class="list-group-horizontal-md">
                        <li *ngIf="asset.data_dictionary_entry.text === selectedAssetText &&  asset.airs.length>0" class="list-inline element-text">{{air}}</li>
                    </ul>
                </div>
            </div>
            <div class="modal-footer">
                <button data-dismiss="modal" class="btn btn-info btn-lg" (click)="saveAsset(asset.value)" type="button">Save</button>
                <button type="button" class="btn btn-danger btn-lg" (click)="modal.close('Cancel')">Cancel</button>
            </div>
        </form>
    </div>

Answer â„–2

After a bit of troubleshooting, I finally discovered my mistake and it turned out to be quite silly. Here's what was happening: I was passing both the assetId and **airText** in the form, but when it reached the saveAsset method, I was trying to access the id instead since the asset contained an id. So, I updated the fields to be id and text, and now I'm successfully able to print the values.

Big thanks to everyone who took the time to read and respond to my question.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript heap runs out of memory in Angular testing because of extensive mock data

While working on testing in angular 4, I encountered a need for large amounts of data in my test cases. Specifically, I needed to dynamically require JSON files in my spec files, each ranging from approximately 4 to 5 MB. As part of the process... it(& ...

Observing the route parameters in an Observable stops once a 404 error is triggered from another Observable within a switchMap

In my current scenario, I am monitoring the parameters of the active route in order to update the content being displayed. Within my component's ngOnInit() function, I have implemented the following logic: this.activeRoute.paramMap .pipe( ...

What is the best way to bring in the angular/http module?

Currently, I am creating an application in Visual Studio with the help of gulp and node. Node organizes all dependencies into a folder named node_modules. During the build process, gulp transfers these dependencies to a directory called libs within wwwroo ...

Issue encountered while defining a component in Angular 16

Currently, I am in the process of learning Angular by following the tutorial provided on Angular.io. As part of this journey, I have declared a home component within my Angular application using the given code: ng generate component home --standalone --in ...

Leveraging components from external modules within sub-modules

So, I've created a module to export a component for use in different modules. However, I'm facing an issue with how to properly utilize this component within child modules of another parent module. While I have imported the first module into the ...

Employ the VSTS node API to retrieve all commits within a specified branch

I have been utilizing the vsts-node-api with reasonable success. However, my goal is to retrieve all commits in a specific branch, as detailed in the REST API documentation located here. Unfortunately, the node api only allows for commit queries in a rep ...

AngularJS: Integrating OAuth2 for RESTful API Development

I am currently working on incorporating OAuth2 authentication into my Angular 2 web project, which relies heavily on REST APIs. I have come across several ng-oauth2 packages that require a new login page for authentication, but I am in need of a restful au ...

Create a chronological timeline based on data from a JSON object

Here is a JSON object generated by the backend: { "step1": { "approved": true, "approvalTime": "10-11-2021", "title": "title 1", "description": "description 1" ...

Query the Firebase database in Angular2 to locate the latitude and longitude values that are nearest to the user's current coordinates

I am working with a database table named locations, which contains a list of places along with their corresponding lat/long coordinates. Additionally, I am utilizing geolocation to retrieve the user's current lat/long. My goal is to identify the loc ...

Transfer the view encapsulation id selector to a CSS class within an @Input directive passed down from the parent component

Alright, we all know that using ng-deep is not ideal and that ViewEncapsulation.None can lead to messy code. So here's the dilemma I'm facing. Let's say I have a component with the following; @Input() cssClasses: string; Now, when I use t ...

Using currency symbols in Angular 2

I'm currently in Australia and trying to display some currency values. I have the following code: {{ portfolio.currentValue | currency : 'AUD' : true : '4.0' }} However, the result I am getting is A$1,300,000. Is there a way to c ...

Angular 17 SSR Swiper 11: Why aren't the breakpoints functioning as expected?

I'm currently struggling with implementing breakpoints in the swiper code. Despite multiple efforts, I have not been able to successfully integrate the breakpoints, and it seems like the functionality is not working as intended. I'm reaching out ...

Facing a challenge with handling HTTP data in a TypeScript-based Angular web application

I am currently working on developing a web application using Angular and the SpringMVC Framework. One of the tasks I'm facing is loading a list of users (referred to as "consulenti" in the code). While the backend HTTP request works fine, I encounter ...

Unable to transfer variable from a function to the test in Protractor

Currently, I am working on a test to verify the amount of gold in my possession. The test is being conducted using TypeScript and Protractor. Within this testing scenario, I have a method named GetAmountOfChips: public static GetAmountOfChips(): PromiseL ...

What is the importance of having typings when using TypeScript?

I recently came across a post on setting up Material-UI for React with Typescript on Stack Overflow: How to setup Material-UI for React with Typescript? As someone who is brand new to typescript, I initially assumed that typescript was simply a superset o ...

There are several InputBase elements nested within a FormControl

There seems to be an issue: Material-UI: It appears that there are multiple InputBase components within a FormControl, which is not supported. This could potentially lead to infinite rendering loops. Please only use one InputBase component. I understand ...

Retrieve the value of [innerHTML] from a subcomponent

I am trying to retrieve the [innerHTML] from a child component Greetings everyone There is a component named 'contact-us' containing the following field. <div [innerHTML] = "legalContent.disclaimer"></div> I have included ...

What is the correct method for integrating jQuery libraries into an Angular project version 10 or higher?

Currently, I am facing difficulties while attempting to install the jquery and jquery-slimscroll packages into an Angular project (version greater than 10). It appears that the installation of these packages has not been successful. In light of this issue, ...

What is the best way to securely store JWT refresh tokens on both the front-end and back-end?

Storing the refresh token on the client side in "Local Storage" poses a significant security risk. If a hacker gains access to this token, they could potentially have everlasting access to the user's account by continually refreshing both access and r ...

Using @carbon/react in conjunction with Next.js version 13 leads to unconventional styling

Here's what I did to set up my Next.js application: npx create-next-app@latest I then installed the necessary package using: npm i -S @carbon/react The global styles in app/globals.scss were customized with this code snippet: @use '@carbon/reac ...