Issue with default selection persisting in Angular 9 when using ngModel

I'm encountering an issue where I am able to successfully autofill a text box based on the state from another component. However, when I attempt to add ngModel to the text box in order to capture the value upon form submission, the value is getting cleared and not being displayed to the user.

<div *ngIf="autoFill; else noFillMode" class="row">
  <label>Mode of Transport</label>
  <input type="text" value="{{state.type}}" readonly />
</div>

<div *ngIf="autoFill; else noFillStop" class="row">
  <label>Nearby Stop / Station</label>
  <input
    type="text"
    value="{{state.stopName}}"
    [(ngModel)]="stopName"
    readonly
  />
</div>

https://i.sstatic.net/iQq7g.png

In the provided image, it is evident that the text appears fine without ngModel on the input. However, the text is not shown when ngModel is added. Can someone offer assistance with this situation?

Answer №1

Implement [(ngModel)] in both input fields

 <div *ngIf="autoFill; else noFillMode" class="row">
        <label>Choose Mode of Transport</label>
        <input type="text" [(ngModel)]="state.type" readonly>
    </div>
        
    <div *ngIf="autoFill; else noFillStop" class="row">
        <label>Nearest Stop / Station</label>
        <input type="text"  [(ngModel)]="state.stopName" readonly>
    </div>

Note: [(ngModel)] facilitates two-way binding for seamless data synchronization between the component and the view.

This bidirectional data binding ensures immediate updates between Model and View components. Any alterations made to the Model(.ts) are instantly reflected in the View(html), and vice versa, maintaining synchronicity at all times.

This real-time and automatic interaction guarantees that changes in the HTML template and TypeScript code are always up-to-date.

Answer №2

When using ngModel, a two-way binding is created. If you're experiencing issues where the input field is empty after adding NgModel, it could be because the stopName attribute is missing in your component. This results in redundancy as both value and ngModel try to set the input value.

To resolve this, consider removing the value attribute and setting existing attributes to ngModel instead.

    <div *ngIf="autoFill; else noFillMode" class="row">
      <label>Mode of Transport</label>
      <input type="text" value="{{state.type}}" readonly>
    </div>

   <div *ngIf="autoFill; else noFillStop" class="row">
     <label>Nearby Stop / Station</label>
     <input type="text" [(ngModel)]="state.stopName" readonly>
   </div>

Another option to consider is using FormControl, which allows you to perform actions such as setting, getting, clearing, and checking validity of values from specific form controls or the entire form.

For a demonstration, check out this implementation on StackBlitz. Don't forget to import ReactiveFormModule.

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

How can I work with numerous "Set-Cookie" fields in NextJS-getServerSideProps?

When working with getServerSideProps, I found a way to set multiple cookies on the client device. This is the code snippet that I used: https://i.stack.imgur.com/Kbv70.png ...

I'm having trouble with fixing the TypeError that says "Cannot read properties of undefined (reading 'style')." How should I address this issue

I'm having trouble with a slideshow carousel on my website. When the site loads, only the first image is shown and you have to either click the corresponding circle or cycle through all the images using the arrows for the image to display. I'm al ...

Determine the maximum and minimum numbers by inputting a number and utilizing jQuery

<script type="text/javascript"> function findLargestNumber() { var number1, number2; number1 = Number(document.getElementById("N").value); number2 = Number(document.getElementById("M").value); if (number1 > numb ...

What could be the reason behind the failure of $cookieStore.get() in retrieving the value?

I am currently testing the cookie functionality in AngularJS. I'm encountering an issue where the console is returning 'undefined' when trying to retrieve a saved value from the cookie using $cookieStore.put(). It seems to work fine when set ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...

Simulation of back-end fetch for backbone model

I am facing an issue with fetching a model using model.fetch();. The model's urlRoot is set to "/backend/item" in my application, but currently I do not have access to the back-end environment. To work around this, I decided to mock the results by add ...

Creating an Image Slideshow on Your Website

I'm looking to create an image slideshow on my website that functions similarly to the one found at . However, I want the images to occupy the entire screen rather than having smaller images like the reference site. Can anyone offer guidance on how t ...

Encountering an issue in Angular 8 where there is a difficulty in reading the property 'NODE_NDEBUG' when attempting to serve the application

An issue has been identified in the assert-plus library at ../node_modules/assert-plus/assert.js where it is encountering difficulties reading 'NODE_NDEBUG' from 'process.env', as highlighted in the code snippet below module.exports = ...

Utilizing Bootstrap Modals to seamlessly redirect me to a new empty page

Despite the fact that my website functions perfectly fine without a build system, I am encountering an issue with the Bootstrap modals while using the Yeoman: Angular + Gulp build system. Whenever I click on a list item, instead of the modal appearing, it ...

Unique title: "Personalized on-click.prevent feature"

I'm having trouble coming up with a name for this concept, so I don't know what specific term to search for. I've checked out some directives, but I'm not convinced that's what I need. Essentially, I want to be able to do the follo ...

Tips for consolidating multiple JavaScript files from various directories into one single file?

I am currently working on a project that involves multiple JavaScript files stored in various folders. My goal is to combine them all into a master.js file. The project structure looks like this: /dist/js/master.js <-- Output file /src/bootstrap-untou ...

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...

The authentication status of req.isAuthenticated for Passport is consistently marked as untrue

I am having issues with my authentication system. Let's start by looking at my node.js file: //Initializing Express Web Server var express = require('express'); var app = express(); var http = require("http").Server(app); var lusca = requi ...

The addEventListener method fails to respond to changes in input

Can someone assist me with this issue? I am facing a problem where the input.addeventlistener is not detecting files on change. My setup involves using Vue with Rails. I am looking to trigger the event listener in the mount hook of a Vue component. mo ...

Ways to imitate an export default function

//CustomConfigurator.ts export default function customizeConfig(name: string): string { // add some custom logic here return output; } //CustomUtility.ts import customizeConfig from './CustomConfigurator'; export default class CustomUtility ...

Maintaining Component State with ngIf in Angular 2

I have a webpage featuring a tab control that occupies a portion of the screen. The tabs are displayed or hidden using *ngIf and checked against an enum to determine which one is selected. As a result, the components are destroyed and created each time the ...

Delivering seamless css integration using express.js

Lately, I've been struggling with serving CSS using Express.js. After some trial and error, I managed to make it work. However, I'm puzzled as to why my new code works while the old one doesn't. Here's the code that now works for me: co ...

Unexpected issue encountered when working with JSON in Node.js

I've searched through countless solutions on stackoverflow, but none of them seem to work for me. It's really frustrating not understanding what's going wrong. Below is the code I'm having trouble with: var data = ""; req.on('dat ...

Modify the height of every div after a successful ajax request

I need assistance in reducing the height of a div within an ajax response that has a class called .shorten-post, but I am unsure how to accomplish this task. I specifically want to decrease the height only for those within the ajax response, not throughou ...

Error: `$(...).fullCalendar is not a function` when using React

After scouring through multiple posts discussing similar issues, I've noticed a common theme of problems arising from improperly loading jQuery or fullcalendar. However, in my case, I have both components loaded into my code (although I can't be ...