简体   繁体   中英

Form not pre-populated Angular 8

I have an API service which returns an array of objects. Each object has two fields name and usage. I am creating a form dynamically where the number of form fields equals the number of objects inside array. Name of the form field is the name and it should be prepopulated with usage value. I am able to create the form and name the form fields but the usage value is not displaying let along correct value in each form field. My TS file code:

ngOnInit() {
    this.apiCall.getArray()
    .subscribe(
      (res: any) => {
        this.receivedData = res;
        for (let i = 0; i < this.receivedData.length; i ++){
          this.currentName  = this.receivedData[i].name;
          this.currentUsage = this.receivedData[i].usage;
          this.name.push(this.currentName);
          this.usage.push(this.currentUsage);
        }

name and usage are arrays where values are stored. In my HTML:

<form>
    <div class="form-row">
      <div class="form-group *ngFor="let plans of name">
        <label>{{plans}}</label>
        <input type="number" min="0" class="form-control" id="usage" name="usage" value="usage" [(ngModel)]="usage">
      </div>
      </div>
      </form>

Now my form fields show correct field names but the fields are empty. They should be pre-filled with respective usage value and the user should be able to change the values as per they wish.

I think there are some problems with your code.

First, if you want to assign a value to an attribute within an Angular *ngFor loop, you need to do something like item.foo . Next to that, square brackets [] are needed to actually pass the value into the attribute and loop through the array of data, because the data is dynamic.

Last problem is that you can't assign numbers (I assumed item.usage would be a number ) to strings like id and name . It's also because you have added the type="number" to the input field.

This will result in the following setup in HTML. I am looping through the data with let item of items and picking the keys where I need them.

<form>
    <div class="form-row">
      <div class="form-group" *ngFor="let item of items">
        <label>{{item.name}}</label>
        <input type="number" min="0" [id]="item.name" [name]="item.name" class="form-control" [(ngModel)]="item.usage">
      </div>
  </div>
</form>

With some mock data it turns out to work.

  received = [
  {
    name: 'Field 1',
    usage: 123456,
  },
  {
    name: 'Field 2',
    usage: 4655454,
  },
  {
    name: 'Field 3',
    usage: 54445,
  }];

See this StackBlitz example for a working example, fixing all of the problems I mentioned earlier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM