app.component.html和app.component.ts之间的通信

时间:2018-06-26 19:21:37

标签: javascript angular forms bootstrap-4

我已经在我的app.component.html文件中构建了一个Angular表单,并且我试图通过app.component.ts文件将字段输入提交给API。如何在.ts文件(将数据传递到API的地方)中引用来自.html文件的输入?

.html文件中的提交按钮的定义如下:

<button (click)="addCust(custJSON)" type="submit" class="btn btn-success" [disabled]="!customerForm.form.valid">Submit</button>

从所有输入字段(也在.html文件中)创建JSON对象:

<script>var custJSON = {{customerForm.value | json}};</script>
{{customerForm.value | json}}

在我的.ts文件中定义的函数:

addCust(custJSON) {
  this.httpClient.post(`api url`,
  {
     custName: custJSON.custName,
     phone: custJSON.phone,
     etc
  })
  .subscribe(
    (data:any) => {
      console.log(data);
    }
  )
}

我现在得到的错误是custJSON未定义。在addCust方法中对数据进行硬编码可以很好地工作,但是目标是将输入从表单上传到API。如何将数据从.html文件获取到.ts文件?

编辑:这是我的表单的更新HTML:

<div class="container">
<form ngNativeValidate (ngSubmit)="onSubmit(customerForm)" action="/action_page.php" name="myForm" #customerForm="ngForm">

<div class="form-group row">
<label for="custName" class="col-sm-2 col-form-label">Name</label>
    <div class="col-sm-10">
        <input type="text" class="form-control" id="custName" placeholder='Name' maxlength=100 required [(ngModel)]="model.custName" name="custName" #custName="ngModel" style="width: 40em">
    </div>
    <div [hidden]="custName.valid || custName.pristine" class="alert alert-danger">
        Name is required
    </div>
  </div>

  <div class="form-group row">
<label for="phone" class="col-sm-2 col-form-label">Phone</label>
  <div class="col-sm-10">
    <input pattern=".{14,14}" type="number" class="form-control" id="phone" placeholder="011 1 111 222 3333" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type = "number" minLength="14" maxLength="14" style="width: 18em" required [(ngModel)]="model.phone" name="phone" #phone="ngModel">
  </div>
<!-- <button class="addfields" type="button" >+</button> -->
<br><div [hidden]="phone.valid || phone.pristine" class="alert alert-danger">
  Phone is required
</div>

  </div>

  <div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email Address</label>
  <div class="col-sm-10">
    <input type="email" class="form-control" id="email" placeholder='ab@cd.com' maxlength=64 required [(ngModel)]="model.email" name="email" #email="ngModel" style="width: 40em">
  </div>
<div [hidden]="email.valid || email.pristine"
     class="alert alert-danger">
  Email Address is required
</div>
  </div>

  <button type="submit" class="btn btn-success" [disabled]="!customerForm.form.valid">Submit</button>

  </form>


    <div [hidden]="!submitted">

    <div class="row">
    <div class="col-xs-3">JSON: <br></div>
    <pre id="result"></pre>
</div>

    <script>var custJSON = new JSON({{customerForm.value | json}});</script>
{{customerForm.value | json}} 

<br><br><br><button class="btn btn-primary" (click)="submitted=false">Edit</button><br><br><br><br><br>

编辑:根据@penleychan进行编辑后,更新了ts文件:

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Customer }    from '../customer';
import { HttpClient } from '@angular/common/http';
import {NgModule, Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import { Injectable } from '@angular/core';
import { Customer } from './customer';
import 'rxjs/add/operator/toPromise';
import { CustomerFormComponent } from './customer-form.component';

@Component({
  selector: 'app-customer-form',
  templateUrl: './customer-form.component.html',
  styleUrls: ['./customer-form.component.css']
})
export class CustomerFormComponent {
  custName:string;
  phone:number;
  email:string;

  model = new Customer('qt', 34823940903812, 't@t');

  submitted = false;

  constructor(private httpClient:HttpClient){  }

  onSubmit(form: NgForm) {
    console.log(form.value);

    this.submitted = true;

    this.httpClient.post<Customer>(`api url`,
      {
         custName: form.value.custName,
         phone: form.value.phone,
         email: form.value.email

         //this.result = form.value;
      })
      .subscribe(
        (data:any) => {
          console.log(data);
        }
      )
    }

  }

}

2 个答案:

答案 0 :(得分:0)

您可以使用角度形式。 例如:

<form [formGroup]="form">
<input formControlName="cust_name" value="cust_name">
<button (click)="addCust()" type="submit">Submit</button>
     </form>

和component.ts

constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      cust_name: ['', Validators.required],
    });
}
addCust() {
          const val = this.form.value;
          this.httpClient.post(`api url`,
          {
            custName: val.cust_name,
          })
          .subscribe(
            (data:any) => {
              console.log(data);
            }
          )
        }

答案 1 :(得分:0)

由于您拥有@Singleton @Component(modules = [AndroidInjectionModule::class, AppModule::class, ActivityBuilder::class ]) interface AppComponent : AndroidInjector<App> { @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder fun build(): AppComponent } override fun inject(app: App) } ,因此不需要按钮上的click事件。因此,只需执行以下操作:

ngSubmit的{​​{1}}上,像这样通过<form>

ngSubmit

从您的按钮中删除NgForm

现在您的组件的打字稿上应该有<form ngNativeValidate (ngSubmit)="onSubmit(customerForm)" action="/action_page.php" name="myForm" #customerForm="ngForm"> 方法了,将其更改一下,现在将是:

(click)="addCust(customerForm)"

为您方便起见,这里https://stackblitz.com/edit/angular-zcjvbt (我删除了手机上的正则表达式进行测试)