PhilipK
PhilipK

Reputation: 63

Set variable from function

This may be an easy question/answer, but I can't seem to wrap my head around it: I am validating fields with a function using AbstractControl:

errorVar: boolean = false

function(c: AbstractControl): {[key: string]: string } | null {
 // validation if 'test' is true or not goes here
 if(test) {
  let errorMessageText: "test"
  return {'errorText': errorMessageText};
 }
return null;
}

Besides the errorText I want the function to also set the variable errorVar to true and to false if the function returns null.

Upvotes: 0

Views: 90

Answers (2)

XouDo
XouDo

Reputation: 961

I think there are several problems

  • your errorVar should be declared using var or let so you can set it in the function via a closure
  • your errorMessageText variable must be set using = and not :

like this:

var errorVar: boolean = false;

function(c: AbstractControl): {[key: string]: string } | null {
    // validation if 'test' is true or not goes here
    if(test) {
        errorVar = true;
        let errorMessageText: string ="test";
        return {'errorText': errorMessageText};
    }
    errorVar = false;
    return null;
}

Upvotes: 0

Hayden Hall
Hayden Hall

Reputation: 356

You can do something like this:

  errorVar: boolean = false

  function(c: AbstractControl): { [key: string]: string } | null {
    // validation if 'test' is true or not goes here
    if (test) {
      this.errorVar = true;
      let errorMessageText:
        return { 'errorText': errorMessageText };
    }

    this.errorVar = false;
    return null;
  }

Upvotes: 1

Related Questions