将表单数据保存到控制台中,角度为2 - 单击“保存”按钮

时间:2017-10-11 12:48:55

标签: javascript json angular

需要帮助,在angular 2应用程序中将数据保存到控制台。

Plunker link

我从json加载的整个数据,标签和相应信息。

我有复杂的json格式,但在这里我制作了简化版本。

问题点击点击保存按钮无法以json格式将数据保存在控制台中

预期:将数据保存在每个受尊重的字段(复选框,文本框)值中,并在单击保存按钮后将其输出到console.log中,稍后我将成为将此数据发送到服务器。

请注意:我尝试过课程和继承,但没有什么对我有用。

enter image description here 任何帮助表示赞赏,我试用一周。

的Json

[
  {
    "id": "tab1",
    "name": "Tab 1",
    "wrapper": [
      {
        "header": "Header goes here",
        "content": [
          {
            "name": "Label 1",
            "id": "tab_1_Type",
            "type": "checkbox",
            "errorType": "green",
            "value": ""
          },
          {
            "name": "Label 2",
            "id": "tab_1_Id",
            "type": "checkbox",
            "errorType": "red",
            "value": ""
          }
        ]
      },
      {
        "header": "Comments",
        "content": [
          {
            "id": "tab_1_Id",
            "type": "textarea",
            "value": ""
          }
        ]
      }
    ]
  },
  {
    "id": "tab2",
    "name": "Tab 2",
    "wrapper": [
      {
        "header": "Header goes here",
        "content": [
          {
            "name": "Text 1",
            "id": "tab_2_Type",
            "type": "checkbox",
            "errorType": "red",
            "value": ""
          },
          {
            "name": "Text 2",
            "id": "tab_2_Id",
            "type": "checkbox",
            "errorType": "green",
            "value": ""
          }
        ]
      },
      {
        "header": "Comments",
        "content": [
          {
            "id": "tab_2_Comments",
            "type": "textarea",
            "value": ""
          }
        ]
      }
    ]
  }
]

app.component.ts

import {Component,ContentChildren,QueryList, OnInit, Injectable, Inject} from '@angular/core';
import {TAB_COMPONENTS} from './tabset';
import {Tab} from './tab';
import { DashboardService } from './app-service';

@Component({
  selector: 'my-app',
  template: `

<div class="col-md-12  pb-2 pt-4">
  <form class="form-horizontal">

<tabset>
  <tab *ngFor="let tab of records" [title]="tab.name"> 
  <div *ngFor="let wrapper of tab.wrapper">
    <div style="text-decoration:underline">{{wrapper.header}}</div>

    <div class="col-md-4" style="margin-bottom:10px;" *ngFor="let name of wrapper.content">
      <label>
        <div [style.background]="name.errorType" style="height:12px; width:12px;display:inline-block "></div>
        <!-- Render checkboxes only if type === checkbox for comment boxes-->
        <input style="display:inline-block" *ngIf="name.type==='checkbox'"  name="{{name.id}}" type="{{name.type}}"> {{name.name}}    
      </label>
    </div>

    <div class="col-md-12" *ngFor="let name of wrapper.content">
      <!-- Render label only if type === textarea for comment boxes-->
      <textarea  class="col-md-12" *ngIf="name.type==='textarea'" name="{{name.id}}"></textarea>
    </div>

  </div>
  </tab>
</tabset>
<button class=" btn btn-primary " href="# " (click)="save() ">Save</button>

</form>
</div>`
})
@Injectable()
export class AppComponent implements OnInit {
  records = [];
  errorMsg: string;

  constructor(@Inject(DashboardService) private _dashboardService: DashboardService) {
    //this.getRecords();
  }

  // getting json values from report.json
  // To build the form
  ngOnInit() {
    this._dashboardService.getRecords()
      .subscribe(
        resGetRecords => {
          debugger;

          this.records = resGetRecords

        },
        resRecordsError => this.errorMsg = resRecordsError
      );
  }

    save(): void {
    console.log(this.error);
  }
}

1 个答案:

答案 0 :(得分:0)

做了一些改动,现在似乎有效。请检查此Plunker

完成修改:

  • 添加了[checked] = "name.value" (change) = "name.value = !name.value"以启用Checkbox的双向数据绑定
  • 添加[(ngModel)]="name.value"以启用Text-area
  • 的双向数据绑定
  • save()内部使用records代替error,因为records是模板中使用的变量,因此它将具有数据绑定值

更新了 app.component.ts

import {Component,ContentChildren,QueryList, OnInit, Injectable, Inject} from '@angular/core';
import {TAB_COMPONENTS} from './tabset';
import { Http, Response, Headers }     from '@angular/http';
import {Tab} from './tab';
import { Error } from './error';
import 'rxjs/add/operator/toPromise';
import { DashboardService } from './app.services';

@Component({
  selector: 'my-app',
  template: `

<div class="col-md-12  pb-2 pt-4">
  <form class="form-horizontal">

<tabset>
  <tab *ngFor="let tab of records" [title]="tab.name"> 
  <div *ngFor="let wrapper of tab.wrapper">
    <div style="text-decoration:underline">{{wrapper.header}}</div>

    <div class="col-md-4" style="margin-bottom:10px;" *ngFor="let name of wrapper.content">
      <label>
        <div [style.background]="name.errorType" style="height:12px; width:12px;display:inline-block "></div>
        <!-- Render checkboxes only if type === checkbox for comment boxes-->
        <input style="display:inline-block" *ngIf="name.type==='checkbox'"  name="{{name.id}}" type="{{name.type}}" [checked] = "name.value" (change) = "name.value = !name.value"> {{name.name}} 
      </label>
    </div>

    <div class="col-md-12" *ngFor="let name of wrapper.content">
      <!-- Render label only if type === textarea for comment boxes-->
      <textarea  class="col-md-12" *ngIf="name.type==='textarea'" name="{{name.id}}" [(ngModel)]="name.value"></textarea>
    </div>

  </div>
  </tab>
</tabset>
<button type="button" class=" btn btn-primary " href="" (click)="save() ">Save</button>

</form>
</div>`
})
@Injectable()
export class AppComponent implements OnInit {
  records = [];
  errorMsg: string;

  constructor(private _dashboardService: DashboardService, private http: Http) {
    this.getRecords();
   }

   // getting json values from configuration.json
   // To build the form
  ngOnInit() {
  this._dashboardService.getRecords()
      .subscribe(
      resGetRecords => this.records = resGetRecords,
      resRecordsError => this.errorMsg = resRecordsError
      );
  }

   // Error object from error.ts
  error: Error;
  private headers = new Headers({ 'Content-Type': 'application/json' });
  private api = './app/report.json';

  // getting json values from report.json
   // To save the form
  getRecords(): Promise<Error[]> {
    console.log(this.api);
    return this.http.get(this.api)
      .toPromise()
      .then(response => {
         response.json().data as Error[]
         this.error = response.json();
         console.log(this.error);
      })
      .catch(this.handleError);
  }

  // On click of save button show console log with values
  save(): void {
    console.log("Inside save");
    console.log(this.records);
  }
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); 
    return Promise.reject(error.message || error);
  }


}