0

I'm following an online course in Angular2 and during a lesson that I was coding along with, I came across an error, but cannot figure out where I went wrong.

I tried to look at similar question around the web but couldn't find any valid solution. The closest I came was this answer, angular2 async form validation, but either the suggestions were irrelevant or it didn't work.

Here is my code:

Component

export class SignUpFormComponent {
   form: ControlGroup;

constructor(fb: FormBuilder){
    this.form = fb.group({
        username: ['', Validators.compose([
            Validators.required, 
            UsernameValidators.cannotContainSpace
        ]), UsernameValidators.shouldBeUnique],
        password: ['', Validators.required]
    });
}

signup(){
    console.log(this.form.value);
}
}

Validators

export class UsernameValidators{
static shouldBeUnique(control: Control){
    console.log("taken");
    return new Promise((resolve, reject) => {
        setTimeout(function(){
            if(control.value == "example")
                resolve({ shouldBeUnique: true });
            else
                resolve(null);
        }, 1000);
    });
}
static cannotContainSpace(control: Control){
    if(control.value.indexOf(" ") >= 0){
        return { cannotContainSpace: true };
    }
    return null;
}
}

Relevant parts of the form

    <input 
        ngControl="username"
        id="username" 
        type="text" 
        class="form-control"
        #username="ngForm">

    <div *ngIf="username.control.pending">Checking for uniqueness...</div>

   <div 
        *ngIf="username.errors.shouldBeUnique"
        class="alert alert-danger">
        Username is already taken.
    </div>

When I run a server locally and start typing into the form the div with the pending message does not appear, and if I type "example" into the input field the error message does not pop up. What am I missing? Thanks.

2
  • For one of many things that may be wrong, I think you input tag gas some error, it should look more like <input ngControl="username" id="username" type="text" class="form-control"> Commented Jun 3, 2017 at 6:02
  • I don't believe there is any problem with the input tag. There are other divs that do properly show up when there is an error, e.g. one div with *ngIf="username.errors.required", which works properly on the page. Commented Jun 5, 2017 at 0:31

1 Answer 1

0

Because I had to change the tsconfig.json file from "target" : "es5" to "target" : "es6", I ran npm install in the terminal again, then ran npm start, which fixed the problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.