在Angular中使用Bootstrap Modal时,有时候会遇到第一次打开Modal时无法正确绑定值的问题。这可能是由于Angular的变更检测机制导致的。
下面是一个解决这个问题的示例代码:
首先,确保在你的项目中已经引入了Bootstrap和jQuery。
在组件的模板文件中,创建一个按钮来打开Modal,并绑定一个点击事件:
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
@ViewChild('content') modalContent: ElementRef;
closeModal: string;
constructor(private modalService: NgbModal) { }
openModal() {
this.modalService.open(this.modalContent, { ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {
this.closeModal = result;
}, (reason) => {
console.log(reason);
});
}
}
Modal Title
通过以上的代码示例,使用[(ngModel)]
来绑定输入框的值,并在Modal的close
和dismiss
事件中传递对应的值。通过这样的方式,可以确保第一次打开Modal时能够正确绑定值。
希望对你有所帮助!