formsangulardata-driven

Use property as form validator in Angular2 (data-driven)


I'm having a hard time trying to set a max value using the data driven approach in Angular2. I want to set the max value of the input to a property called userLimit, which I get from firebase. This is my code:

component.ts

import { Component, OnInit, AfterViewInit  } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms";
import { FiredbService } from '../services/firedb.service';
import { AuthService } from '../services/auth.service';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';

@Component({
  selector: 'my-dashboard',
  styleUrls: ['./recibirpago.component.scss'],
  templateUrl: './recibirpago.component.html'
})
export class RecibirpagoComponent implements OnInit, AfterViewInit {

  myForm2: FormGroup;
  uid: string;
  userLimit: any;

  constructor(private fb: FormBuilder,
              private dbfr: FiredbService,
              private db: AngularFireDatabase,
              private authService: AuthService) {

     this.myForm2 = this.fb.group({
      email: ['', Validators.email],
      clpmount: ['', [Validators.required, Validators.max(this.userLimit)]]
      });

   }

ngOnInit() {
    this.uid = this.authService.getUserUid();
} 

ngAfterViewInit() {
  this.dbfr.getUserLimit(this.uid).subscribe(snapshot => {          
    this.userLimit = snapshot.val().accountLimit;
    console.log(this.userLimit);
    })
}

If I write, for example, Validators.max(5000) it works, but if I try to get the data from Firebase it doesn't work.

Thanks for your help!


Solution

  • The problem is that the constructor is executing before the ngAfterViewInit so you don't have the value of the userLimit at that point.

    Instead use the setVAlidators method within the subscribe where you get the data.

    Something like this:

    constructor

     this.myForm2 = this.fb.group({
      email: ['', Validators.email],
      clpmount: ['', Validators.required]  // <-- not here
      });
    

    ngAfterViewInit

    ngAfterViewInit() {
      this.dbfr.getUserLimit(this.uid).subscribe(snapshot => {          
        this.userLimit = snapshot.val().accountLimit;
        console.log(this.userLimit);
        const clpControl = this.myForm2.get(`clpmount');
        clpControl.setValidators(Validators.max(this.userLimit)); // <-- HERE
        clpControl.updateValueAndValidity();
        })
    }
    

    NOTE: Syntax was not checked.