ng-bootstrap 警报不会关闭

ng-bootstrap alerts won't close

单击 X 按钮时我的通知不会关闭。

我已经使用 angular cli 创建了一个新的应用程序。我按照说明 here 加载 bootstrap:

npm install bootstrap@4.0.0-alpha.6  

然后我按照说明 here 加载 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>
...

警报出现,并且样式正确,但当我单击 X 时它没有关闭。其他组件正在工作(选项卡集、下拉列表)。我在 app.component.ts 中遗漏了什么吗?

您必须在组件中定义一个 close 事件方法。

HTML:

<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;
}

希望对您有所帮助。

这已经很晚了,但可能会帮助其他人寻找一个简单的可关闭警报。该组件包装了 Devansh 解决方案:

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';
}

用法:

<app-alert>I'm a closeable alert!</app-alert>