Как использовать код для открытия модального в Angular 2?
Обычно мы используем data-target="#myModal"
в <button>
, чтобы открыть модальный. Прямо сейчас мне нужно использовать коды для управления, когда нужно открыть модальный.
Если я использую [hidden]
или *ngIf
, чтобы показать его, мне нужно удалить class="modal fade"
, в противном случае модальная никогда не будет отображаться. Вот так:
<div [hidden]="hideModal" id="myModal">
Однако в этом случае после удаления class="modal fade"
модальность не будет исчезать и не имеет тени в фоновом режиме. И что еще хуже, оно будет отображаться на дне экрана, а не на экране.
Есть ли способ сохранить class="modal fade"
и использовать код для его открытия?
<button type="button" data-toggle="modal" data-target="#myModal">Open Modal</button>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
</div>
</div>
</div>
Ответы
Ответ 1
Это один из способов найти. Вы можете добавить скрытую кнопку:
<button id="openModalButton" [hidden]="true" data-toggle="modal" data-target="#myModal">Open Modal</button>
Затем используйте код "click" для открытия модального файла:
document.getElementById("openModalButton").click();
Этот способ может поддерживать стиль начальной загрузки модального и затухающего в анимации.
Ответ 2
Включить jQuery как обычно внутри тегов script в index.html.
После импорта, но до объявления @Component, добавьте:
declare var $: any;
Теперь вы можете использовать jQuery в любом месте вашего Angular 2 TypeScript кода:
$("#myModal").modal('show');
Ссылка: fooobar.com/questions/30176/...
Ответ 3
Простой способ достичь этого в angular 2 или 4 (предположим, что вы используете загрузочный файл 4)
Component.html
<button type="button" (click)="openModel()">Open Modal</button>
<div #myModel class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title ">Title</h5>
<button type="button" class="close" (click)="closeModel()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
</div>
</div>
</div>
Ответ 4
Вот моя полная реализация модального компонента начальной загрузки angular2:
Я предполагаю, что в вашем основном файле index.html(с тегами <html>
и <body>
) в нижней части тега <body>
у вас есть:
<script src="assets/js/jquery-2.1.1.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
modal.component.ts:
import { Component, Input, Output, ElementRef, EventEmitter, AfterViewInit } from '@angular/core';
declare var $: any;// this is very importnant (to work this line: this.modalEl.modal('show')) - don't do this (becouse this owerride jQuery which was changed by bootstrap, included in main html-body template): let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
@Component({
selector: 'modal',
templateUrl: './modal.html',
})
export class Modal implements AfterViewInit {
@Input() title:string;
@Input() showClose:boolean = true;
@Output() onClose: EventEmitter<any> = new EventEmitter();
modalEl = null;
id: string = uniqueId('modal_');
constructor(private _rootNode: ElementRef) {}
open() {
this.modalEl.modal('show');
}
close() {
this.modalEl.modal('hide');
}
closeInternal() { // close modal when click on times button in up-right corner
this.onClose.next(null); // emit event
this.close();
}
ngAfterViewInit() {
this.modalEl = $(this._rootNode.nativeElement).find('div.modal');
}
has(selector) {
return $(this._rootNode.nativeElement).find(selector).length;
}
}
let modal_id: number = 0;
export function uniqueId(prefix: string): string {
return prefix + ++modal_id;
}
modal.html:
<div class="modal inmodal fade" id="{{modal_id}}" tabindex="-1" role="dialog" aria-hidden="true" #thisModal>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" [ngClass]="{'hide': !(has('mhead') || title) }">
<button *ngIf="showClose" type="button" class="close" (click)="closeInternal()"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<ng-content select="mhead"></ng-content>
<h4 *ngIf='title' class="modal-title">{{ title }}</h4>
</div>
<div class="modal-body">
<ng-content></ng-content>
</div>
<div class="modal-footer" [ngClass]="{'hide': !has('mfoot') }" >
<ng-content select="mfoot"></ng-content>
</div>
</div>
</div>
</div>
И пример использования в компоненте Editor клиента:
клиент-редактировать-component.ts:
import { Component } from '@angular/core';
import { ClientService } from './client.service';
import { Modal } from '../common';
@Component({
selector: 'client-edit',
directives: [ Modal ],
templateUrl: './client-edit.html',
providers: [ ClientService ]
})
export class ClientEdit {
_modal = null;
constructor(private _ClientService: ClientService) {}
bindModal(modal) {this._modal=modal;}
open(client) {
this._modal.open();
console.log({client});
}
close() {
this._modal.close();
}
}
клиент-edit.html:
<modal [title]='"Some standard title"' [showClose]='true' (onClose)="close()" #editModal>{{ bindModal(editModal) }}
<mhead>Som non-standart title</mhead>
Some contents
<mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
</modal>
Параметры заголовка, showClose, mhead и mfoot ar.
Ответ 5
Лучший способ, который я нашел. Поместите #lgModal
или другое имя переменной в ваш модальный.
На ваш взгляд:
<div bsModal #lgModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" (click)="lgModal.hide()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Large modal</h4>
</div>
<div class="modal-body">
...
</div>
</div>
</div>
</div>
В вашем компоненте
import {Component, ViewChild, AfterViewInit} from '@angular/core';
import {CORE_DIRECTIVES} from '@angular/common';
// todo: change to ng2-bootstrap
import {MODAL_DIRECTIVES, BS_VIEW_PROVIDERS} from 'ng2-bootstrap/ng2-bootstrap';
import {ModalDirective} from 'ng2-bootstrap/ng2-bootstrap';
@Component({
selector: 'modal-demo',
directives: [MODAL_DIRECTIVES, CORE_DIRECTIVES],
viewProviders:[BS_VIEW_PROVIDERS],
templateUrl: '/app/components/modals/modalDemo.component.html'
})
export class ModalDemoComponent implements AfterViewInit{
@ViewChild('childModal') public childModal: ModalDirective;
@ViewChild('lgModal') public lgModal: ModalDirective;
public showChildModal():void {
this.childModal.show();
}
public hideChildModal():void {
this.childModal.hide();
}
ngAfterViewInit() {
this.lgModal.show();
}
}
Ответ 6
Ответ ниже относится к последней версии ng-bootstrap
устанавливать
npm install --save @ng-bootstrap/ng-bootstrap
app.module.ts
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [
...
],
imports: [
...
NgbModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Контроллер компонентов
import { TemplateRef, ViewChild } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-app-registration',
templateUrl: './app-registration.component.html',
styleUrls: ['./app-registration.component.css']
})
export class AppRegistrationComponent implements OnInit {
@ViewChild('editModal') editModal : TemplateRef<any>; // Note: TemplateRef
constructor(private modalService: NgbModal) { }
openModal(){
this.modalService.open(this.editModal);
}
}
Компонент HTML
<ng-template #editModal let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Edit Form</h4>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="dateOfBirth">Date of birth</label>
<div class="input-group">
<input id="dateOfBirth" class="form-control" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker #dp="ngbDatepicker">
<div class="input-group-append">
<button class="btn btn-outline-secondary calendar" (click)="dp.toggle()" type="button"></button>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close()">Save</button>
</div>
</ng-template>
Ответ 7
Думаю, я нашел правильный способ сделать это с помощью ngx-bootstrap. Сначала импортируйте следующие классы:
import { ViewChild } from '@angular/core';
import { BsModalService, ModalDirective } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
Внутри реализации класса вашего компонента добавьте свойство @ViewCild, функцию для открытия модального окна и не забудьте настроить modalService как частное свойство внутри конструктора класса компонентов:
@ViewChild('editSomething') editSomethingModal : TemplateRef<any>;
...
modalRef: BsModalRef;
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template);
}
...
constructor(
private modalService: BsModalService) { }
Часть editSomething объявления @ViewChild относится к файлу шаблона компонента и его реализации модального шаблона (#editSomething):
...
<ng-template #editSomething>
<div class="modal-header">
<h4 class="modal-title pull-left">Edit ...</h4>
<button type="button" class="close pull-right" aria-label="Close"
(click)="modalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
(click)="modalRef.hide()"
>Close</button>
</div>
</ng-template>
И, наконец, вызовите метод, чтобы открыть модальное место, где вы хотите, вот так:
console.log(this.editSomethingModal);
this.openModal( this.editSomethingModal );
this.editSomethingModal - это TemplateRef, который может быть показан ModalService.
И вуаля! Модал, определенный в файле шаблона вашего компонента, показывается вызовом изнутри вашей реализации класса компонента. В моем случае я использовал это, чтобы показать модальный режим из обработчика событий.
Ответ 8
Как я это делал без большого количества кодировок.
У меня есть скрытая кнопка с id="employeeRegistered"
В моем .ts
файле я import ElementRef from '@angular/core'
Затем после того, как я обработаю все на моем методе (click)
, выполните следующие действия:
this.el.nativeElement.querySelector('#employeeRegistered').click();
тогда модальные дисплеи, как ожидалось.
Ответ 9
Для меня мне пришлось установить тайм-аут в дополнение к решению @arjun-sk (ссылка), так как я получал ошибку
setTimeout(() => {
this.modalService.open(this.loginModal, { centered: true })
}, 100);
Ответ 10
Я использую переменную для управления показом и скрытием и полагаюсь на кнопку "открыть модал"
код ts:
showModel(){
this.showModal = true;
}
HTML:
<button type="button" data-toggle="modal" data-target="#myModal" (click)="showModel()>Open Modal</button>
<div *ngIf="showModal" >
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
</div>
</div>
</div>
Ответ 11
Мы можем использовать jquery, чтобы открыть модал начальной загрузки.
ngAfterViewInit() {
$('#scanModal').modal('show');
}
Ответ 12
попробуйте использовать это ng-окно для angular2
https://github.com/BahgatMashaly/ng-window
![]()