2

I have a form,and when i submit the form the form data is submitting to the angular firebase database.so if we sigin again i want to show the data into the form which has been submitted before.

my .ts file is below

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder,Validators } from "@angular/forms";
import { AF } from "app/providers/af";
import { FirebseService } from "app/firebse.service";
import { Router } from "@angular/router";
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';

@Component({
  selector: 'app-candidate-registration',
  templateUrl: './candidate-registration.component.html',
  styleUrls: ['./candidate-registration.component.css']
})
export class CandidateRegistrationComponent implements OnInit {
  itemsAsObjects = [{value: 0, display: 'Angular'}, {value: 1, display: 'React'}];
  complexForm : FormGroup;
  contents:any;


  constructor(fb: FormBuilder,
               private firebaseService:FirebseService,
               private router: Router,
               private db: AngularFireDatabase) {

                var Userid=localStorage.getItem('user');
                console.log(Userid); 
                let content= this.db.object('/candidates_list/'+Userid)
                content.subscribe(data => {
                          console.log(data);
                          this.contents=data;
                          console.log(this.contents);
                        })
     if(this.contents){
        this.complexForm = fb.group({
      // To add a validator, we must first convert the string value into an array. The first item in the array is the default value if any, then the next item in the array is the validator. Here we are adding a required validator meaning that the firstName attribute must have a value in it.
              'firstName' : ["pranav", Validators.required],
              // We can use more than one validator per field. If we want to use more than one validator we have to wrap our array of validators with a Validators.compose function. Here we are using a required, minimum length and maximum length validator.
              'lastName': ["kk", Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(10)])],
              'gender' : [null, Validators.required],
              'email' : [null, Validators.required],
              'contact_number':[null, Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(10)])],
              'experience':[null, Validators.required],
              'skills':[null, Validators.required],
              'notice_period':[null, Validators.required],


            })
    }else
            {
              this.complexForm = fb.group({
              // To add a validator, we must first convert the string value into an array. The first item in the array is the default value if any, then the next item in the array is the validator. Here we are adding a required validator meaning that the firstName attribute must have a value in it.
              'firstName' : [null, Validators.required],
              // We can use more than one validator per field. If we want to use more than one validator we have to wrap our array of validators with a Validators.compose function. Here we are using a required, minimum length and maximum length validator.
              'lastName': [null, Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(10)])],
              'gender' : [null, Validators.required],
              'email' : [null, Validators.required],
              'contact_number':[null, Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(10)])],
              'experience':[null, Validators.required],
              'skills':[null, Validators.required],
              'notice_period':[null, Validators.required],


            })
    }


  }

  ngOnInit() {


  }
  submitForm(user){

       console.log(user);
       this.firebaseService.addtolist(user);
       this.complexForm .reset();
       this.router.navigate(['/reg-complete']);


  }

}

this below code(part of .ts file) is working fine.i am getting the signed in users data into console.But i dont know how to use it into if condition, to set the data of the already signed in users into the registration form. anyone please help me?Thanks in advance.

var Userid=localStorage.getItem('user');
                    console.log(Userid); 
                    let content= this.db.object('/candidates_list/'+Userid)
                    content.subscribe(data => {
                              console.log(data);
                              this.contents=data;
                              console.log(this.contents);
                            })
pranavyoyo
  • 75
  • 1
  • 6
  • Have you tried the ``setValue()`` ? You can use ``this.complexForm.setValue()`` to set the form fields with the data you get from HTTP GET . – CruelEngine Jun 17 '17 at 18:00

1 Answers1

0

Well, the main problem here is that when you check this statement:

if (this.contents) { ... }

It will always go to else.

Why? Because the async operation where you define this.contents isn't resolved yet, and as you didn't defined an initial value for this.contents, it's undefined.

For a deep explanation I'd suggest you to check this question.


That said, I want to suggest another approach to solve your problem:

Instead of having the if/else with full duplicate code, let's break it into a method, like this:

initForm(data: Object = {}) {
  this.complexForm = fb.group({
    firstName: [data.firstName, Validators.required],
    lastName: [data.lastName, [Validators.required, Validators.minLength(1), Validators.maxLength(10)],
    gender: [data.gender, Validators.required],
    email: [data.email, Validators.required],
    contact_number: [data.contact_number, [Validators.required, Validators.minLength(10), Validators.maxLength(10)],
    experience: [data.experience, Validators.required],
    skills: [data.skills, Validators.required],
    notice_period: [data.notice_period, Validators.required]
  });
}

Explanation:

In the signature method I'm initializing data as a clean object, so if nothing or undefined | null is passed to the function it'll automatically become a clean object like this {}.

It's useful because it prevents the undefined.<property> errors.

Full code:

constructor(private fb: FormBuilder,
            private router: Router,
            private db: AngularFireDatabase,
            private firebaseService:FirebseService) {
  const userId = localStorage.getItem('user');

  if (userId) {
    this.db.object(`/candidates_list/${userId}`)
    .subscribe(data => {
      this.contents = data; // This variable isn't used anymore.
      this.initForm(data);
    });
  } else {
    this.initForm();
  }
}

initForm(data: Object = {}) {
  this.complexForm = fb.group({
    firstName: [data.firstName, Validators.required],
    lastName: [data.lastName, [Validators.required, Validators.minLength(1), Validators.maxLength(10)],
    gender: [data.gender, Validators.required],
    email: [data.email, Validators.required],
    contact_number: [data.contact_number, [Validators.required, Validators.minLength(10), Validators.maxLength(10)],
    experience: [data.experience, Validators.required],
    skills: [data.skills, Validators.required],
    notice_period: [data.notice_period, Validators.required]
  });
}

Notes:

1 - The Validators.compose isn't needed, you can just pass an array, or if it's a single validator, the validator itself, in both parameters (2nd and 3rd).

2 - I'd suggest you to move this code from constructor to ngOnInit.

3 - You can face some error in template since the complexForm won't be filled until the async operation is resolved (when you have a user stored, of couse).

To be more specific it'll throw this error:

ORIGINAL EXCEPTION: formGroup expects a FormGroup instance. Please pass one in.

So, you'll have to use some flag to handle the form in template.

Supposing that you've something like this in your template:

<form [formGroup]="complexForm">
  ...
</form>

You can solve solve this doing the following:

Component:

import 'rxjs/add/operator/finally';

...

isLoading: boolean = true;

...

this.db.object(`/candidates_list/${userId}`)
.finally(() => this.isLoading = false)
.subscribe(data => {
  this.contents = data;
  this.initForm(data);
});

Template:

<ng-container *ngIf="!isLoading">
  <form [formGroup]="complexForm">
    ...
  </form>
</ng-container>
developer033
  • 24,267
  • 8
  • 82
  • 108