What is the best way to set up the user's editable information in the input field?

Is it possible for a user to edit their data? I have made the data accessible on this page, stored in information. I would like the user to see their data upon entering the view, such as their username or email, and be able to edit or delete it. I initially attempted using placeholders, but they are not the actual input. I also tried initializing the data in my form, but that did not work either.

This is what I have attempted:

page.html

...
    <ion-item class="input-item">
                  <ion-label color="secondary" position="floating">Username</ion-label>
                  <ion-input type="text" formControlName="username" required></ion-input>
                </ion-item>
...

page.ts

ngOnInit() {
      if (this.authService.authenticationState) {
      this.storage.get(USER_ID).then(val => {
        this.id = val;
        console.log(this.id);
        this.userService.getUserDetails(this.id).subscribe(result => {
          this.information = result;
          console.log(this.information);
        });
      });
    }


      this.updateUserForm = new FormGroup({
        username: new FormControl('', Validators.required),
        email: new FormControl('', Validators.compose([
          Validators.required,
          Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
        ])),
        birthdate: new FormControl(Validators.required),
        gender: new FormControl(this.genders[0], Validators.required),

      });

  }

Answer №1

To set initial values for your form fields in the definition of your FormGroup, you can do the following:

this.userProfileForm = new FormGroup({
      username: new FormControl(this.data ? data.username : "", Validators.required),
      email: new FormControl(this.data ? data.email : "", Validators.compose([
        Validators.required,
        Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
      ])),
      birthdate: new FormControl(Validators.required),
      gender: new FormControl(this.genders[0], Validators.required),
});

Update

If data is fetched asynchronously, make use of FormControl.setValue() as shown below:

userProfileForm: FormGroup;

ngOnInit() {
    if (this.authService.isAuthenticated) {
        this.storage.get(USER_ID).then(val => {
            this.id = val;
            this.userService.getUserDetails(this.id).subscribe(response => {
                this.userProfileForm.get("username").setValue(response.username);
                this.userProfileForm.get("email").setValue(response.email);

                // When field names match with response keys, you can directly set values using:
                // this.userProfileForm.setValue(response);
            });
        });
    }

    this.userProfileForm = new FormGroup({
        username: new FormControl('', Validators.required),
        email: new FormControl('', Validators.compose([
            Validators.required,
            Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
        ])),
        birthdate: new FormControl(Validators.required),
        gender: new FormControl(this.genders[0], Validators.required),
    });
}

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

Exploring the implementation of Javascript, HTML, PHP, and Ajax in programming

<div class="navigation"> <a class="prev" href="index.php?month=__prev_month__" onclick="$('#calendar').load('index.php?month=__prev_month__&_r=' + Math.random()); return false;"></a> <!-- <div class="title" & ...

create parameters for the angular properties of chemical functions

I have two functions that clear cancer and reproductive dropdowns individually. Now, I want to combine these functions into a parametrized function that takes a chemical input: clearDropdown(chemical) { switch (chemical) { case 'cancer& ...

How can I utilize JavaScript to generate a dynamic value in a URL and then submit it through a form?

One of my clients has requested the ability to send out unique URLs to their customers in order to track which links are being utilized. Despite my suggestion to use Google Analytics for this purpose, they have specifically asked to avoid it. Their reques ...

"Using an indexer in TypeScript allows for direct access to object properties by simply specifying the key within

I have a requirement to access an object property using a string as the key interface MyObject { prop1: string; prop2: string; prop3: string; prop4: string; prop5: string; } let initialValues: MyObject; //I initialize some properties initialVa ...

What is the most effective way to organize and display objects, such as using an "interest" attribute that could be the same for multiple "User" objects?

Hey everyone, I'm facing some challenges while trying to create a function. In the code snippet provided, I aim to develop the interestMatch function. The goal of this function is to analyze all users and identify those who share the same interest - s ...

Incorporating the chosen value from a dropdown box as a variable in PHP

Seeking assistance with using the value selected in a drop-down box as a PHP variable in my functions.php file. I attempted to utilize jquery-ajax for this purpose. $(document).ready(function(){ $("#pa_color").change(function(){ var result= $(this).val( ...

Issue encountered with edges helper and a partly opaque object rendering

My goal is to create a realistic earth using three.js, similar to this example, which is an improvement from this one. However, I am facing an issue where the rendering order of the sky, earth, and atmosphere is not being properly interpreted by the render ...

Is it possible that an error is triggered when utilizing canActivate or canChildActivate?

A problem has arisen while using canActivateChild or canActivate in the child route. Despite working fine previously, an error is now being thrown: ERROR in src/app/app-routing.module.ts(8,7): error TS2322: Type '({ path: string; redirectTo: string; ...

I want to showcase a Python array within an Angular framework

Here is an example array: [ { "TO":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2b6a7b1b682a5afa3abaecca1adaf">[email protected]</a>", "FROM":"<a href="/cdn-cgi/l/email-protection" class="__ ...

Group multiple typescript files into separate outFile modules

Can TypeScript files be grouped into multiple outFiles? I want to bundle my Typescript code, but instead of one single JS file, I would like to organize my TS into separate JS files such as controllers.js and plugins.js. The options in the TypeScript pro ...

Drag and Drop File Upload with Angular 2

I'm currently working on incorporating a drag and drop upload feature for angular 2, similar to the one found at: Given that I am using angular 2, my preference is to utilize typescript as opposed to jquery. After some research, I came across a libra ...

Error: The value of 'v4' property is not defined and cannot be read

I am encountering an issue with Vue.js: vue.esm.js?efeb:628 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'v4' of undefined" found in ---> <AddTodo> at src/components/AddTodo.vue <App> at src/Ap ...

What is the best way to incorporate a button that, when clicked, reveals two separate images on the frontend?

describe food option heredescribe juice option hereHow can I create a button using HTML, CSS, JavaScript, and Bootstrap that displays different images for food and juices when clicked? For example, clicking on "food" will display 3 different food images, w ...

Analyzing past UTC date times results in a peculiar shift in time zones

When I receive various times in UTC from a REST application, I encounter different results. Examples include 2999-01-30T23:00:00.000Z and 1699-12-30T23:00:00.000Z. To display these times on the front end, I use new Date(date) in JavaScript to convert the ...

"The Ajax function for replacing a div upon change event is not functioning properly

I am having an issue with my select box using the onchange event, <select class="form-control" onchange="getval(this.value,'<?php echo $prd->pr_id;?>','ajax<?php echo $key?>','<?php echo $key ?>')"&g ...

Having trouble receiving a response from axios

My goal is to use axios to submit a blog post and display a response message. If the response is "success," the process should proceed. For testing purposes, I am only using console.log("success ok"). However, I encountered a puzzling issue that I cannot f ...

The static folder in Express server is failing to serve files

I have an application with certain static files that I want to send to the client, however the server is not sending them. app.use(express.static(__dirname, '/public')); I need help fixing this particular code snippet. ...

Importing a JS file within a JS script

Currently, I am facing a requirement to dynamically include a .js file (more jQuery code) within a working jQuery script. Specifically, when my page gets authenticated, I need to add a specific script file. I am looking to accomplish this in ASP.Net MVC. ...

How can I automate the process of clicking each button on a page one by one simultaneously?

I'm looking for a way to add a small delay of 1 second after each button is clicked in my code. I want the buttons to be clicked one after the other, not all at once. How can I achieve this until all buttons are clicked? Below is the current code: v ...

Transform the checkbox selection into an active hyperlink upon being selected

Currently, I am in the process of designing a form that allows visitors to select items they would like to view by checking relevant checkboxes. Upon clicking a Request button, the URLs of the selected items are displayed. I aim to have the URL appear as ...