Home > front end >  How to use validator to change border color of formcontrolname in angular
How to use validator to change border color of formcontrolname in angular

Time:11-25

I have a formcontrol where I want to change the color when the field is invalid I have tried the following as most examples do the same:

 <input 
        formControlName="personNameField"
        type="text"
        placeholder="Bitte eingeben"
        [ngClass]="{'error': personNameField.errors}"
        ></input>
    

My ts formcontrol is generated like this:

    form = this.builder.group({
    personNameField: new FormControl('',
      [Validators.required]),
  });

  getName(){
    this.form.get('personNameField')
  }

But I am getting the following error:

ERROR TypeError: Cannot read properties of undefined (reading 'errors')

any idea what I am doing wrong?

UPDATE: I added the getter and removed the question mark but still the bordering does not work only error message is shown.

UPdate2:

.error {
    // underline input field on error
    border: 1px solid red;
    display: block;
    color: red;
}

What I want target image

What I get what i get

CodePudding user response:

Try this.

[ngClass]="{'error': form.get('personNameField')?.errors}"

CodePudding user response:

so simple for input validation using bootstrap class : First in you HTML file we have :

        <div class="form-group">
        <label for="title">title</label>
        <input id="title" type="text" formControlName="title" class="form- 
       control" [ngClass]="{'is-invalid': isCategorySubmitted && 
        categoryFormInfo.title.errors}" />
        </div>

so in your ts file :

isCategorySubmitted = false;

initFormBuilder() {
this.categoryForm = this.formBuilder.group({
  title: ['', Validators.required]
});

}

  get categoryFormInfo() {
return this.categoryForm.controls;

}

  submit() {
this.isCategorySubmitted = true;
if (this.categoryForm.invalid) {
  return;
}

  // do your code after the submit

}

by this, you can validate the input so simply .

  • Related