我在我的角度应用程序(v6)中使用 bootstrap 4 modal :
代码:
<div class="container">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Open
</button>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
Modal body..
</div>
</div>
</div>
</div>
</div>
现在,我将通过单击open
按钮来打开模式。效果很好。但是,无需手动打开它,在单击open
按钮时,我需要致电method/function
来致电
open() {
if('Some condition'){
// Don't open the modal
} else {
// Open the modal
}
}
在open()
方法中,如果条件失败,modal
应该打开,否则不应该打开。我如何仅使用typescript
答案 0 :(得分:1)
您需要使用@ViewChild
指令来实现此目的。只需添加以下代码:
<!-- The Modal -->
<div class="modal" id="myModal" #content>
<div class="modal-dialog">
...... further code
在component.ts文件中:
export class AppComponent implements OnInit {
@ViewChild('content') content: any;
public ngOnInit() {
}
public open() {
if(!true){
// Dont open the modal
} else {
// Open the modal
this.content.open();
}
}
更新后的堆叠闪电战: https://stackblitz.com/edit/angular-ckggpk
答案 1 :(得分:0)
您也可以使用* ngIf来显示具有某些布尔值的模态对话框。
import { Component, OnInit, ViewChild } from '@angular/core';
import {
FormBuilder,
FormGroup,
Validators,
} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
showModalBox: boolean = false;
public ngOnInit() {
}
public open() {
if(0){
// Dont open the modal
this.showModalBox = false;
} else {
// Open the modal
this.showModalBox = true;
}
}
}
<div class="container">
<button type="button" class="btn btn-primary" data-toggle="modal" (click)="open()" data-target="#myModal">
Open modal
</button>
<!-- The Modal -->
<div *ngIf="showModalBox" class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
Modal body..
</div>
</div>
</div>
</div>
</div>
Stackblitz:https://stackblitz.com/edit/angular-2ngwu1
答案 2 :(得分:0)
使用ng bootstrap即可。引导模式演示https://stackblitz.com/edit/angular-j2e63j?file=app%2Fmodal-basic.ts
更多信息,请参见此https://ng-bootstrap.github.io