My alerts won't close when I click the X button.
I've used angular cli to create a new app. I followed the instructions here to load bootstrap:
npm install [email protected]
Then I followed instructions here to load ng-bootstrap:
npm install --save @ng-bootstrap/ng-bootstrap
app.module.ts:
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [
AppComponent,
NavComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
NgbModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Testing...';
}
app.component.html
<app-nav></app-nav>
<ngb-alert>Alert</ngb-alert>
...
The alert shows up, and is styled properly, but it doesn't close when I click the X. Other components are working (tabset, dropdown). Am I missing something in app.component.ts?
Closing Alerts To close the alert message, add a . alert-dismissible class to the alert container. Then add class="close" and data-dismiss="alert" to a link or a button element (when you click on this the alert box will disappear).
ngb-alert – It's a directive which is used to display a bootstrap alert in our Angular app. dismissible – It's a property which is used to display close (cross) button on the right corner of the alert. If set true, close button will be displayed otherwise not.
Bootstrap Alerts are used to provide an easy way to create predefined alert messages. Alert adds a style to your messages to make it more appealing to the users. There are four classes that are used within <div> element for alerts. .alert-success.
You have to define a close
event method in your component.
<ngb-alert *ngIf="!closed" (close)="closed=true">Alert</ngb-alert>
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Testing...';
closed = false;
}
I hope this will help you.
This is very late but might help others looking for a simple closeable alert. This component wraps Devansh's solution:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-alert',
template: '<ngb-alert [type]="type" *ngIf="open" (close)="open=false"><ng-content></ng-content></ngb-alert>',
})
export class InfoPanelComponent {
public open = true;
@Input() type = 'info';
}
usage:
<app-alert>I'm a closeable alert!</app-alert>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With