The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't seem to work. It's probably a simple mistake due to my lack of experience with Angular.

One-way binding (using []) works fine, but when I add () to the HTML tags, it stops working.

Here is an excerpt from the HTML code of my custom component:

<form class="form_MyProfile">
  <table class="myprofile_width" cellspacing="0">
    ...
   </table>
  </form>

And here is part of the TypeScript code from the same component:

@Component({
 selector: 'app-my-profile',
 templateUrl: './my-profile.component.html',
 styleUrls: ['./my-profile.component.css']
 } )
...
 loadProfile(): void {
 this.repo.getData('api/Profile')
   .subscribe((res: UserRegister) => {
     this.userProfile = res;
     //assigning values to variables here
   },
     error => {
       this.alertService.error(error);
     });
   }

The method loadProfile makes an API call that retrieves the data successfully, but setting the values doesn't seem to work as expected.

If anyone can identify the issue, I would greatly appreciate your help.

Have a wonderful day,

Lio

Answer №1

Make sure to use the same name for both the input field and ngModel as the model in your typescript file:

<form class="form_MyProfil">
  <table class="myprofil_width" cellspacing="0">
    <tr>
      <td>
        <mat-form-field class="myprofil_width">
          <input matInput [(ngModel)]="username" name="username" placeholder="Username"  disabled>
        </mat-form-field>
      </td>
    </tr>
    <tr>
      <td>
        <mat-form-field class="myprofil_width">
          <input matInput [(ngModel)]="password" name="password" placeholder="New password" [type]="hide ? 'password' : 'text'">
          <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
        </mat-form-field>
      </td>
    </tr>

    <tr>
      <td>
        <mat-form-field class="myprofil_width">
          <input matInput [(ngModel)]="email" name="email" placeholder="Your Email" required>
        </mat-form-field>
      </td>
    </tr>
    <tr>
      <td>
        <mat-form-field class="myprofil_width">
          <input matInput [(ngModel)]="town" name="town" placeholder="Town"  type="text" required>
        </mat-form-field>
      </td>
    </tr>
   </table>
  </form>

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

Managing HTTP requests across different HTML pages in a Cordova mobile application

I have developed a Multiple Page Application (MPA) for Android and iOS which navigates to different pages when users want to view them. Everything is running smoothly so far, but I now want to add some backend sync features. The issue I am facing is that I ...

Having trouble retrieving the Ionic 2 slides instance - getting a result of undefined

As I attempt to utilize the slides and access the instance in order to use the slideto functionality programmatically, I find myself encountering the issue of receiving 'undefined' back despite following the documentation. Here is my TypeScript ...

JavaScript User Information Lookup Module

My goal: I am trying to create a function that will check if the firstName provided matches an existing contact's firstName in the contacts array, and if the prop specified is a valid property of that contact. If both conditions are met, the functio ...

Improper menu alignment following a MenuItem hover event within Material-UI

When a MenuItem is hovered over, the position of the Menu container should remain unchanged. [x] The issue persists in the most recent release. However, downgrading MUI to v4.5.0 results in the expected behavior. Current Behavior ...

I am looking to set an HTML file as the homepage for my Next.js project

Is there a way in next.js to render a normal .html file (index.html) when someone visits my root directory at "https://example.com/"? I have researched and edited my config file as shown below, /** @type {import('next').NextConfig} */ const next ...

How to access an element from the JSON return value retrieved from an AJAX call using JavaScript

After making an ajax call that returns successfully, I am facing a problem. I cannot access individual elements of the array it returns, and therefore unable to console log it. The error message indicates that the track is not defined, even though it is pr ...

Unlocking the Power of Transition: Effortlessly Submitting a Form Post

After the modal finishes fading out, I want my form to be submitted and sent to the email file "refreshform.php". However, currently after the modal fades out, the form does not submit or post anything to the PHP file for sending the email. It simply fades ...

JavaScript Canvas - Preserve Image Transparency

I have been trying to download a snapshot of a canvas using the code below: var strMime = "image/png"; var canvas = document.getElementsByTagName('canvas')[0]; var link = document.createElement("a"); link.href = canvas.toDataURL( ...

Ensuring Map Safety in Typescript

Imagine having a Map structure like the one found in file CategoryMap.ts export default new Map<number, SubCategory[]>([ [11, [100, 101]], [12, [102, 103]], ... ]) Is there a way to create a type guard for this Map? import categoryMap fro ...

Unsteady movement of Three JS OrbitControls during rotation

Currently, I am working on a scene with three.js and using orbit controls to rotate the camera around the scene. Occasionally, while rotating, the camera starts moving erratically before calming down and rotating smoothly again. I have read about orbit co ...

Menu only appears with a double click on the label button

Currently, I'm facing an issue where I have to click the label "button" (hamburger menu) twice in order to show the menu for the second time. My belief is that there might be a conflict between CSS and jQuery causing this behavior. The desired funct ...

In order to use the serve command, it is necessary to run it within an Angular project. However, if a project definition cannot be located

An error occurred while running the ng serve command: C:\Mysystem\Programs\myfwms>ng serve The serve command needs to be executed within an Angular project, but a project definition could not be found. I encounter this error when ...

When a user clicks on a button, AJAX and jQuery work together to initiate a setInterval function that continually

Currently, I have two scripts in place. The first script is responsible for fetching a specific set of child nodes from an XML file through AJAX and using them to create a menu displayed as a list of buttons within #loadMe. What's remarkable about thi ...

Displaying the current time and total time of a custom video player using Javascript

Currently, I'm in the process of creating an html5 video player and have incorporated javascript to update the current time as a fraction of the total time. The script I've written so far is as follows: function updateTime() { var curTime = ...

Is it possible to utilize v-html with message data in Vue without any limitations on the <title> element?

Currently utilizing Vue.js 2 and my SDK is IntelliJ: I am attempting to bring HTML content into a Vue.js file. The main objective is to include the <title></title> attribute, as it seems that Vue doesn't have direct support for this feat ...

Error: A stream was expected, but instead you provided an object that is invalid. Acceptable options include an Observable, Promise, Array, or Iterable

I attempted to use map with a service call and encountered an error. After checking this post about 'subscribe is not defined in angular 2', I learned that for subscribing, we need to return from within the operators. Despite adding return statem ...

Utilizing JavaScript to trigger an email with PHP variables included

i am trying to pass a few php variables using a javascript trigger. Everything seems to be working with the variables, databases, and script but I am struggling with the PHP part. Here is my attempt at the PHP code, although it clearly has some issues. I ...

Tips for extracting year, month, and day from a date type in Typescript

I'm currently working with Angular 7 and I'm facing some challenges when it comes to extracting the year, month, and day from a Date type variable. Additionally, I am utilizing Bootstrap 4 in my project. Can anyone assist me with this? Below is ...

The React Vite application encountered an issue: There is no loader configured for ".html" files at ../server/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html

**Encountered errors in a React Vite web app** ** ✘ [ERROR] No loader is configured for ".html" files: ../server/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html ../server/node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js:86 ...

How can I create a reverse animation using CSS?

Is there a way to reverse the animation of the circular notification in the code provided? I want the circle to move forward, covering up the info and fading out. I've tried switching the animation around but haven't had success. Any suggestions? ...