Home > Blockchain >  How to attach bootstrap 5 .is-invalid to Angulars ng-invalid?
How to attach bootstrap 5 .is-invalid to Angulars ng-invalid?

Time:01-13

Bootstrap 5 has a class to mark input fields as invalid (.is-invalid).

enter image description here

I'm using a reactive form and when my input is "invalid" the "ng-invalid" style is added. Is there a way to change this style to .is-invalid to match the Bootstrap class?

html form:

<div >
  <label for="lastNameInput" >Achternaam</label>
  <input
    formControlName="lastName"
    type="text"
    
    id="lastNameInput"
  />
</div>

In typescript I created my form:

this.membersForm = this.fb.group({
  name: new UntypedFormControl('', Validators.required),
  lastName: new UntypedFormControl('', Validators.required),

CodePudding user response:

You can change the style of the "ng-invalid" class to match the Bootstrap class ".is-invalid" by using Angular's ngClass directive. You can bind the "ng-invalid" class to the ".is-invalid" class in your HTML template. Here's an example of how you can do this for your input field:

<div >
   <label for="lastNameInput" >Achternaam</label>
   <input
     formControlName="lastName"
     type="text"
     
     [ngClass]="{'is-invalid': membersForm.get('lastName').invalid && 
      membersForm.get('lastName').touched}"
     id="lastNameInput"
   />
</div

Here, we are using the ngClass directive to bind the "is-invalid" class to the input field when the "lastName" form control is invalid and has been touched by the user. This will add the "is-invalid" class to the input field and style it according to the Bootstrap class, while still preserving the functionality of the "ng-invalid" class.

CodePudding user response:

just "duplicate" the class

.form-control.ng-invalid.ng-touched {
  border-color: #dc3545;
  padding-right: calc(1.5em   .75rem);
  background-image: url("data:image/svg xml,");
  background-repeat: no-repeat;
  background-position: right calc(.375em   .1875rem) center;
  background-size: calc(.75em   .375rem) calc(.75em   .375rem);
}
.form-control.ng-invalid.ng-touched:focus,.form-check-input.ng-invalid.ng-touched:focus{
  border-color: #dc3545;
  box-shadow: 0 0 0 .25rem rgba(220,53,69,.25);
}
.form-check-input.ng-invalid.ng-touched
{
  border-color: #dc3545;
}
.ng-invalid.ng-touched ~ .form-check-label
{
  color:#dc3545
}
.ng-invalid.ng-touched ~ .invalid-feedback
{
  display: block;
}

e.g.

 <div >
    <label for="lastNameInput" >Achternaam</label>
    <input
      [formControl]="lastName"
      type="text"
      
      id="lastNameInput"
    />
    <div >Please provide a valid city.</div>
  </div>

stackblitz

  • Related