typescript angular2 提交表单值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43197902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:25:14  来源:igfitidea点击:

angular2 submitting form values

angulartypescript

提问by Saroj Maharjan

I need to get the form values but when I console.log the parameter in profile-create.ts that I had passed from profile-create.html I get value undefined and I need to save the form values to database. I am not being able to figure out this issue.

我需要获取表单值,但是当我 console.log 从 profile-create.html 传递的 profile-create.ts 中的参数时,我得到的值未定义,我需要将表单值保存到数据库中。我无法弄清楚这个问题。

>> Profile-create.component.html

<!--<md-dialog-content>-->

<form class="add-contact-form" #f="ngForm" (ngSubmit)="submitForm(value)">
  <div class="md-dialog-header">
    <h1 md-dialog-title>
     <md-icon> person_add</md-icon>
  Add Account Profile
  </h1>
 </div>
 <div md-dialog-content>
   <div class="form-group">
     <label>Legal Name</label>
     <input type="text"  [(ngModel)]="profile.dbaName" required>
   </div>
  <div class="form-group">
    <label>DBA Name</label>
    <input type="text" [(ngModel)]="profile.status" required>
  </div>
  <div class="form-group">
    <label>Address</label>
    <input type="text" required>
  </div>
  <div class="form-group">
    <label>Email Address</label>
    <input type="text" required>
  </div>
</div>
<div md-dialog-actions>
  <button md-button (click)="dialogRef.close('cancel')">CANCEL</button>
  <button type="submit" class="btn btn-success" [disabled]="!f.form.valid">Submit</button>
</div>

profile-create.component.ts

profile-create.component.ts

import { Component, OnInit } from '@angular/core';
import { MdDialogRef } from '@angular/material';
import { Router } from '@angular/router';

import { CookieService } from 'angular2-cookie/services/cookies.service';

import { AppConstant } from '../../../shared/constant/app-constant';
import { ProfileService } from '../profile.service';
import { Profile } from '../profile';
import { UrlConstant } from '../../../shared/constant/url-constant';

@Component({
  selector: 'app-profile-create',
  templateUrl: './profile-create.component.html',
  styleUrls: ['./profile-create.component.scss', '../../shared/assets/dialog.scss'],
  providers: [CookieService, ProfileService]
})
export class ProfileCreateComponent implements OnInit {

  constructor(
    public dialogRef: MdDialogRef<ProfileCreateComponent>,
    private profileService: ProfileService,
    private cookieService: CookieService,
    private router: Router) {
  }

  ngOnInit(){
  }

  profile: Profile = new Profile("hello" , "active" , true);

  submitForm(val){
    console.log(val , "OOOOOOOO");
    this.dialogRef.close('form submitted');

    const authToken: string = this.cookieService.get(AppConstant.AUTH_TOKEN_COOKIE);
const organizationId: string = this.cookieService.get(AppConstant.SIGN_IN_ORGANIZATION_ID_COOKIE);

this.profileService.createProfile({ authToken: authToken }, { organizationId: organizationId } , val)
      .subscribe((profile) => {
        this.router.navigate([`/admin/${UrlConstant.PROFILES}/`, profile.id]);
      })
   }
}

profile.ts

profile.ts

 export class Profile {
  id: number;
  dbaName: string;
  status: string;
  isDefault: boolean;
  address: string;
  phoneNumber: string;
  legalName: string;
  language: string;
  timezone: string;
  email: string;

  constructor(dbaName: string, status: string, isDefault:boolean) {
    this.dbaName = dbaName;
    this.status = status;
    this.isDefault = isDefault;
  }
}

profile.service.ts

profile.service.ts

import { Injectable } from "@angular/core";
import { Http, Headers, Response } from "@angular/http";
import { Observable } from "rxjs/Rx";
import { Profile } from "./profile";
import { environment } from "../../../environments/environment";
import { UrlConstant } from "../../shared/constant/url-constant";

@Injectable()
export class ProfileService {
  constructor(private http: Http) {
  }

  private headers = new Headers({ 'Content-Type': 'application/json' });
  private authApiUri = environment ['BP_AUTH_SERVER_URI'];


createProfile(headers, path, data): Observable<Profile> {
     this.headers.set('Authorization', headers.authToken);
    return  this.http.post(`${this.authApiUri}/${UrlConstant.PROFILE_LIST.replace(':organizationId', path.organizationId)}`, data, { headers: this.headers })
      .map(response => {
        const profileResponse = response.json().account;
        let profile = new Profile(profileResponse.dbaName, profileResponse.status, profileResponse.isDefault);
        profile.id = profileResponse.id;
        return profile;
     })
      .catch(this.handleError);
  }

回答by Vinit Sarvade

Your submit method is passing the wrong parameter. You need to pass the local reference that you have created. i.e. (ngSubmit)="submitForm(f)". And in your method you can access the form values like

您的提交方法传递了错误的参数。您需要传递您创建的本地引用。即(ngSubmit)="submitForm(f)"。在您的方法中,您可以访问表单值,例如

submitForm(form) {
     console.log(form.value);
}

回答by Roger Jacob

As per Angular 2, you need to add name attribute along with ngModel like and now from the component you can access the input fields.

根据 Angular 2,您需要添加 name 属性以及 ngModel 之类的,现在您可以从组件访问输入字段。

回答by Sajeetharan

what is value as a parameter inside the submitForm? You do not have to pass any parameter. Just change it like this,

什么是submitForm 中的参数值?您不必传递任何参数。改成这样就好了

<form class="add-contact-form" #f="ngForm" (ngSubmit)="submitForm(f)">

and inside the Component.ts

并在 Component.ts 中

doSubmit(form) {
 console.log(form.value);
}

}

}