Búsqueda de sitios web

angular - angular2 enviando los valores del formulario


Necesito obtener los valores del formulario, pero cuando hago console.log del parámetro en profile-create.ts que había pasado desde profile-create.html, obtengo el valor undefined y necesito guardar los valores del formulario en la base de datos. No he podido resolver este problema.

>> 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>

perfil-crear.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]);
      })
   }
}

perfil.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;
  }
}

perfil.servicio.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);
  }

Respuesta #1

Tu método submit está pasando el parámetro incorrecto. Necesitas pasar la referencia local que has creado. Es decir, (ngSubmit)="submitForm(f)". Y en tu método puedes acceder a los valores del formulario como

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

Respuesta #2

Según Angular 2, necesitas agregar el atributo name junto con ngModel y ahora desde el componente puedes acceder a los campos de entrada.