Issues with updating form inputs in Ionic 2's FormGroup item

Hey there, I'm just getting started with Angular 2 and I've been working on creating a basic form using FormBuilder and FormGroup. However, for some reason, the value I input into the username field in my view is not updating in my component. When I click the submit button, I don't see the new value reflected. Below is the code for both my view and component - could someone please help me identify what might be causing this issue?

login.ts

import { Component} from "@angular/core";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
selector:"login-page",
templateUrl: "login.html"
})

export class LoginPage {
    loginForm : FormGroup;
    constructor(formBuilder :FormBuilder) {
        this.loginForm = formBuilder.group({
            'username':[
                '',
                Validators.required
            ]
        });
    }

     validate() : boolean {
         if (this.loginForm.valid) {
             return true;
         }
     }
    submit() : void {
        if (!this.validate()) {
            console.info("Invalid input")
        }
        let control = this.loginForm.controls['username'].value;
        console.log(control);
    }
}

login.html

<ion-header style="text-align:center">
  <ion-navbar>
    <ion-title>Please login</ion-title>
  </ion-navbar>
</ion-header>


<ion-content padding>

    <h3 style="text-align:center">Welcome to your first Ionic app!</h3>


   <form class ="list" [formGroup]="loginForm" (ngSubmit)="submit()">
      <ion-item class="loginInput center">
          <ion-label floating>Email</ion-label>
          <ion-input type="text" name='username' ngControl="username" ></ion-input>
      </ion-item>
      <div class="loginBtn"><button  style="width: 140px" ion-button type="submit">Login</button></div>
   </form>

</ion-content>

Answer №1

Revise the following code:

<ion-input type="text" name='username' ngControl="username" ></ion-input>

With this updated version:

<ion-input type="text" [formControl]="loginForm.controls['username']" ></ion-input>

Answer №2

Make the following modifications.

.ts

loginForm : FormGroup;

constructor(formBuilder :FormBuilder) {
   this.loginForm = formBuilder.group({
      username:['',Validators.required]
   });
}

.html

 <form class ="list" [formGroup]="loginForm" (submit)="submit(loginForm)">
    <ion-item class="loginInput center">
       <ion-label floating>Email</ion-label>
       <ion-input type="text" name='username' formControlName="email" ></ion-input>
    </ion-item>
    <div class="loginBtn">
       <button style="width: 140px" ion-button type="submit">Login</button>
    </div>
 </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

Designing a Tombstone with TypeScript

In TypeScript, I have certain values that are only necessary within the type system and not at runtime. I am seeking a way to void these values without losing their type information. The function bury illustrated below is intended to replace the actual v ...

Using Systemjs with Angular 2 results in 50 server calls for loading resources

While following the Angular2 quickstart tutorial on Angular.io, I noticed that it was making 50 separate requests, which left me wondering why. https://i.sstatic.net/bqMk8.png Is there a way to consolidate all these requests into one? My goal is to have ...

Issues installing dependencies in Angular using npm

Today I attempted to create a new project. I used the following command: ng new NAME --style=less However, when I ran this command in my cmder, it resulted in errors and warnings. To troubleshoot, I decided to uninstall Node.js along with the files in R ...

Guide on creating rsa key pair on the client side with angular2

Is there a way to generate an 'rsa' key-pair on the client-side using angular2? I am looking to create a private/public key pair and store the private key in a database while using the public key on the client side. How can this be achieved? I c ...

Angular2: Issue with service injection within service

Below is the code snippet I have written. Assuming you can grasp the purpose without further elaboration. @Injectable() export class Dispatcher { } @Injectable() export class TodoStore { constructor(@Inject(Dispatcher) private dispatcher:Dispatcher ...

How can I export a function signature in TypeScript?

Is there a specific syntax to export a function from another module in an interface or a namespace? I couldn't find the right way to do it. What would be the correct syntax? import {myFunction} from './a' export interface MyInterface { ...

What's the Advantage of Using a Getter for a Public Field in Angular?

Having come from a background in Java where the practice is to make variables as private as possible, I've noticed in Angular that private fields are not used frequently. What is the reasoning behind not making fields private if it's possible? ...

Zod Entry using standard encryption key

I'm attempting to define an object type in zod that looks like this: { default: string, [string]: string, } I've experimented with combining z.object and z.record using z.union, but the validation results are not as expected. const Local ...

Typescript: The property 'userId' is not found within the 'unknown' type

For my rxJS practice in Typescript, I wrote the following simple code. import fetch from 'node-fetch'; import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, SubscriptionLike, PartialObserver } from &apo ...

Facing issues with query parameters functionality

For my Angular2 application, I need to include some optional parameters in a route. Since they are not mandatory, I have opted to utilize the queryParams feature. This is the code snippet I am using to pass the optional argument: public recoverPassword() ...

Creating a navigation bar that smoothly slides into view from the top

In my Angular app (version 2+), the current code I have is: .header { background: rgba(white, 0); &.fixed-top { background: rgba(white, 1); border-bottom: solid whitesmoke 1px; position: fixed; top: 0; right: 0; left: 0; ...

Obtaining the time taken for code execution in Typescript by capturing console.timeEnd() as

Can the value of console.timeEnd() be captured as a variable in Typescript? I need it for debugging but am unable to view console outputs while testing on my phone. If not, is there a simple alternative method to achieve this without relying on external G ...

Terminal displays Typescript variable syntax error

Recently, I've been delving into TypeScript using Visual Studio Code. However, I've encountered a perplexing syntax error that stems from how I've defined a variable. Here's an example of my declaration: let year:number = 2015 My term ...

Converting a String to JSON Formatting

Require assistance. I am currently working with two strings saved in separate variables; var var1 = "Myname"; var var2 = "Myage"; var jsonObj = ? console.log(jsonObj); I aim to transform the console output of "jsonObj" i ...

The kendo-angular-chart is missing the required dependency kendo-charts-1.19.1.tgz

Is anyone else experiencing issues with the kendo-chart installation? I am attempting to install kendo-angular-chart and encountering the following problem: npm install npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.org/@progress/ ...

Issue with the deprecated router package in Angular 2 rc3

Welcome Angular 2 rc.3! After following the instructions in the 5 Min Quickstart and using project.json to configure my project, I encountered an error when running npm install: No compatible version found: @angular/<a href="/cdn-cgi/l/email-protectio ...

Creating eye-catching designs for Material grid-list items

Here is the code snippet for generating a list: <md-grid-list cols="5" rowHeight="20px"> <md-grid-tile *ngFor="let carBrand of carBrands" colspan= 1 rowspan= 1> <md-checkbox>{{ carBrand}}< ...

I encountered an error when attempting to retrieve a JSON from a URL using a previously provided solution. What might be causing this issue?

Currently, I am facing an issue while trying to retrieve a JSON file for my memory card game. Even after following the solution provided in this question: How to get json file from HttpClient?, I encounter an error message that is quite confusing for me: h ...

In TypeScript, use a key index signature for any properties that are not explicitly defined

In various instances, I have encountered scenarios where it would have been beneficial to implement the following (in a highly abstracted manner): export interface FilterItem { [key: string]: string | undefined; stringArray?: string[]; } However, thi ...

What methods does Angular use to differentiate between router-outlet tags that are located in various components?

Within the app.component.html, we include a < router-outlet > tag that dynamically loads other modules, components, and views. However, if we have a second component (imported in a different module) with its own < router-outlet > How does Ang ...