在其他组件中使用后,NgBootstrap错误

时间:2018-08-17 09:12:39

标签: angular ng-bootstrap

  

错误错误:“ ExpressionChangedAfterItHasBeenCheckedError:表达式   检查后已更改。上一个值:'className:   未定义”。当前值:“ className:模态背景淡入淡出”。它   好像该视图是在其父级和子级之后创建的   已经脏了检查。是否已在变更检测中创建它   钩?”

在组件中:

constructor(private modalService: NgbModal) {}

open() {
        const modalRef = this.modalService.open(ModalChoiceComponent);
}

ngOnInit() {this.open();}

以我的方式:

import {Component, OnInit} from '@angular/core';
import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-modal-choice',
    template: `
    <div class="modal-header">
      <h4 class="modal-title">Hi there!</h4>
      <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <p>Hello, World!</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-outline-dark" (click)="activeModal.close('Close click')">Close</button>
    </div>
  `
})
export class ModalChoiceComponent implements OnInit {

  constructor(public activeModal: NgbActiveModal) { }

  ngOnInit() {
  }

}

在我的AppModule中:

import {BrowserModule} from '@angular/platform-browser';
import {NgModule, APP_INITIALIZER} from '@angular/core';
[...]
import { MainComponent } from './main/main.component';
import {AppComponent} from './app.component';
import {NgbModalModule} from '@ng-bootstrap/ng-bootstrap';
import { ModalChoiceComponent } from './modal-choice/modal-choice.component';


export function init_app(config: ConfigService) {
    return () => config.initialize();
}

@NgModule({
    declarations: [
        AppComponent,
        [...]
        MainComponent,
        ModalChoiceComponent
    ],
    imports: [
        BrowserModule,
        [...]
        NgbModalModule
    ],
    providers: [],
    bootstrap: [AppComponent],
    entryComponents: [
        ModalChoiceComponent
    ]
})
export class AppModule {
}

我真的不知道是什么问题。我遵循了“ ngBootstrap”文档中的确切示例。

1 个答案:

答案 0 :(得分:0)

Angular表单指令具有根据焦点更改同步更新的绑定  模态将焦点带到窗口

** 要解决此问题,请使用event.preventDefault()和blur()方法

将对象传递给打开方法

<input type="text" [readonly]="true" placeholder="Please select a user" (focus)="open($event)" formControlName="username" class="form-control"/>

open(event) {
        event.srcElement.blur();
        event.preventDefault();
        const modalRef = this.modalService.open(ModalChoiceComponent);
}

示例:https://stackblitz.com/edit/angular-1oedu4