У меня есть угловое приложение. Я хочу открыть модальное всплывающее окно Bootstrap, когда пользователь нажимает ссылку в нижнем колонтитуле. Ниже мой модальный код Bootstrap.
<button type = "button" class = "btn btn-primary" data-toggle = "modal" data-target = "#exampleModalCenter">
Launch demo modal
</button>
<div class = "modal fade" id = "exampleModalCenter" tabindex = "-1" role = "dialog" aria-labelledby = "exampleModalCenterTitle" aria-hidden = "true">
<div class = "modal-dialog modal-dialog-centered" role = "document">
<div class = "modal-content">
<div class = "modal-header">
<h5 class = "modal-title" id = "exampleModalCenterTitle">Modal title</h5>
<button type = "button" class = "close" data-dismiss = "modal" aria-label = "Close">
<span aria-hidden = "true">×</span>
</button>
</div>
<div class = "modal-body">
...
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-secondary" data-dismiss = "modal">Close</button>
<button type = "button" class = "btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Ниже находится footer.component.html файл
<footer class = "text-center text-lg-start bg-light text-muted fixed-bottom">
<div class = "text-center p-2" style = "background-color: gray;">
Copyright 2001-2022. All rights reserved. For internal use only.
<a class = "text-reset" data-toggle = "collapse"
[attr.data-target] = "'#exampleModalCenter'">Terms of Use | </a>
<a class = "text-reset" href = "https://mdbootstrap.com/">Privacy Statement</a>
</div>
</footer>
Где мне нужно хранить модальный код, в footer.component или в отдельном компоненте? Как я могу открыть это, когда пользователь щелкает якорную ссылку «Условия использования» в нижнем колонтитуле?
Я использую эти версии:
"bootstrap": "5.2",
"@angular/core": "^14.2.0"
Прежде всего, вы, кажется, используете библиотеку начальной загрузки для ванильного javascript и HTML. Вам следует подумать о переходе на «Bootstrap с поддержкой Angular» (https://ng-bootstrap.github.io/#/), чтобы использовать преимущества angular. Вы получите те же компоненты, но сможете внедрять разные модули в ваше угловое приложение.
После этого вы должны создать новый компонент, содержащий код вашего всплывающего окна.
Затем вы можете внедрить NgbModal в компонент нижнего колонтитула следующим образом:
Затем вы можете открыть модальное окно при нажатии кнопки, используя constructor(private modalService: NgbModal) {}
Более подробную информацию о том, как открывать модальные окна из компонентов angular, можно найти здесь: https://ng-bootstrap.github.io/#/components/modal/examples
Вот как я это исправил. Сначала добавьте nb bootstrap в свой проект.
ng add @ng-bootstrap/ng-bootstrap
Если вы получаете ошибки при добавлении ng bootstrap. Сначала запустите команду ниже, затем попробуйте команду выше.
npm config set legacy-peer-deps true
Теперь в footer.component добавьте код ниже
<footer class = "text-center text-lg-start text-muted fixed-bottom">
<div class = "text-center p-2" style = "gray;">
Copyright 2001-2022. All rights reserved. Confidential.
<a class = "text-reset" [routerLink] = "" style = "cursor:pointer;" data-toggle = "collapse"
(click) = "open(mymodal)">Terms of Use | </a>
<a class = "text-reset" href = "https://mdbootstrap.com/">Privacy Statement</a>
</div>
</footer>
<!-- Modal -->
<ng-template #mymodal let-modal>
<div class = "modal-header">
<h4 class = "modal-title">Terms of Use</h4>
<button type = "button" class = "btn-close" aria-label = "Close" (click) = "modal.dismiss('Cross click')"></button>
</div>
<div class = "modal-body">
<p>
Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam.
Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
</p>
<p>
Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet
rutrum faucibus dolor auctor.
</p>
<p>
Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.
Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.
</p>
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-light" (click) = "modal.close('Close click')">Close</button>
</div>
</ng-template>
Добавьте приведенный ниже код в файл footer.component.ts
import { Component, OnInit } from '@angular/core';
import { ModalDismissReasons, NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {
closeResult: string = '';
constructor(private modalService: NgbModal) { }
ngOnInit(): void {
}
open(content:any) {
this.modalService.open(content, { scrollable: true, ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
}
Когда вы нажмете ссылку «Условия использования» в нижнем колонтитуле, вы увидите всплывающее окно с моделью, как показано ниже, в центре экрана.