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

Azure Function (.NET 7, v4) encountering Cross-Origin Resource Sharing problem

I am experiencing a CORS problem with my Azure function written in C# using .NET 7. It is being called from my Angular application. Interestingly, the same function works fine when called from Postman with the same request body as the Angular application. ...

What is the process for initiating a local Lambda edge viewer request?

Is there a way to run aws cloudfront lambda edge functions locally and simulate the event in order to observe the response from one of the four functions? I made modifications to the viewerRequest function of lambdaEdge, but I'm wondering if there is ...

Transferring an array of data across different screens within an Ionic 2 application

I am a newcomer to Ionic 2 and I am encountering difficulties when it comes to passing data between pages. Within my Home.ts file, there exists a global array containing certain numbers that have been calculated. My intention is to transfer this array to m ...

"Converting the Request Body into Encoded

One challenge I am facing is the need to encode the body of all outgoing requests in my Angular application, including standard json. While using HttpClient to make requests, it appears that I do not have direct access to the serialization layer within Ang ...

Angular Material's dialog modal swiftly closes without delay

Could you please explain why the modal opens and then closes instantly when I click on the Create Project button? https://example.com/edit/angular-code I am trying to display a component within the modal using Angular Material. portafolio.component.ts ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

Encountering an installation issue with Angular 2 data table

Is there a solution for resolving unmet peer dependencies during the installation of Angular 2 data table? Here is the issue I am encountering while trying to install it. ...

Encountering NaN in the DOM while attempting to interpolate values from an array using ngFor

I am working with Angular 2 and TypeScript, but I am encountering NaN in the option tag. In my app.component.ts file: export class AppComponent { rooms = { type: [ 'Study room', 'Hall', 'Sports hall', ...

Steps for updating the value of a button in Typescript and React

I currently have a button that manages my language switcher, configured to handle cookies, URL changes, and now I want it to update the translations on the page as well. The <img> tag is utilized for changing the country flag. < ...

Capture individual frames from angular video footage

Trying to extract frames from a video using Angular has been quite challenging for me. While browsing through Stack Overflow, I came across this helpful post here. I attempted to implement the first solution suggested in the post, but unfortunately, I was ...

React Hot Toast useState is unfortunately not exported from the React library

While working on a Next.js project, I encountered an issue when trying to use react-hot-toast. When I attempted to import it into any file, I received the following error message: Error - ./node_modules/react-hot-toast/dist/index.mjs Attempted import erro ...

Count duplicated values in an array of objects using JavaScript ES6

I am working on creating a filter for my list of products to count all producers and display them as follows: Apple (3) I have managed to eliminate duplicates from the array: ["Apple", "Apple", "Apple"] using this helpful link: Get all non-unique values ...

Currently in motion post file selection

I am currently facing an issue with a button that triggers a file selector pop-up. Below is the code snippet: <button mat-raised-button (click)="inputFile.click()">Choose a file</button> <input #inputFile type="file" [style.display]="' ...

Tips on leveraging an attribute for type guarding in a TypeScript class with generics

Is there a way to utilize a generic class to determine the type of a conditional type? Here is a basic example and link to TS playground. How can I access this.b and this.a without relying on as or any manual adjustments? type X<T> = T extends true ...

Express displays html instead of json when error handling occurs

I recently followed a tutorial on Express.js to create a simple error handler. function clientErrorHandler(err, req, res, next) { if (req.xhr) { console.log('clienterrorhandler', err); res.status(500).send({ error: 'Something faile ...

Containerizing Next.js with TypeScript

Attempting to create a Docker Image of my Nextjs frontend (React) application for production, but encountering issues with TypeScript integration. Here is the Dockerfile: FROM node:14-alpine3.14 as deps RUN apk add --no-cache tini ENTRYPOINT ["/sbin ...

How to convert typescript path aliases into relative paths for NPM deployment?

I am currently working on a typescript project that utilizes paths for imports. For instance: "paths": { "@example/*": ["./src/*"], } This allows the project to import files directly using statements like: import { foo } from "@example/boo/foo"; Whe ...

The necessary package required for my library is missing (@angular/material/core not found)

I have developed a custom Angular library called @foo/bar, and it has the following dependencies: "peerDependencies": { "@angular/common": "^10.0.14", "@angular/core": "^10.0.14" }, "depend ...

Tips for wrapping text in a column within material-ui's DataGrid

Struggling to apply word wrap to my column header title in DataGrid from material-ui. I've attempted using sx and style with no success. I even tried this: const StyledDataGridtwo = styled(DataGrid)<DataGridProps>(({ theme }) => ({ root: { ...

'The signatures of each of these values are not compatible with one another.' This error occurs when using find() on a value that has two different array types

Here's the code snippet I'm attempting to run within a TypeScript editor: type ABC = { title: string } type DEF = { name: string } type XYZ = { desc: ABC[] | DEF[] } const container: XYZ = { desc: [{title: & ...