Bootstrap alert auto close in Angular 14

Viewed 18

I used the bootstrap alert to show the success messages and the failure message. We cn close that alert box by using the "X". But I am not able find a way so that the alert box closes after 3 sec automatically.

.html snippet

<div *ngIf="errorMsg" class="alert alert-danger alert-dismissible fade show" role="alert">
        <strong [innerHTML] = "errorMsg"></strong> 
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close</button>
 </div>

.ts snippet

userSubmit() {
    var errors = [];

    console.log(this.userForm.get('image').value);
    console.log(this.userForm.value);
    const formData = new FormData();
    formData.append('image', this.images);
    formData.append('id', this.userForm.value.id);
    formData.append('des', this.userForm.value.des);
    formData.append('name', this.userForm.value.name);

    if (
      this.userForm.value.id < '100000' ||
      this.userForm.value.id > '9999999'
    ) {
      errors.push('ID should be greater of 6 or 7 digits.');
    } if (
      this.userForm.value.name.match(/[^A-Za-z ]/)
    ) {
      errors.push( 'Name should contain only alphabets.');
    } if (
      this.userForm.value.des.match(/[^A-Za-z ]/)
    ) {
      errors.push( 'Designation should contain only alphabets.');
    } 

    if(errors.length != 0){

      this.errorMsg = errors.join('<br>');
      console.log(this.errorMsg);

      
    }else{
      this.service.createData(formData).subscribe((res) => {
        console.log(res);
        this.userForm.reset();
        this.successMsg = res.message;
      });
    }
1 Answers

use setTimeout in your component to set your errorMsg property to null after 3 sec something like

 if(errors.length != 0){
    this.errorMsg = errors.join('<br>');
    setTimeout(() => {
       this.errorMsg=null;
    }, 3000);
    console.log(this.errorMsg); 
}
Related