gpt4 book ai didi

angular - 如何关闭 Angular 2 中的模式?

转载 作者:太空狗 更新时间:2023-10-29 16:54:39 24 4
gpt4 key购买 nike

我希望用户单击“提交”按钮并自动关闭模式。

如果我添加 data-dismiss="modal"在提交<button> , 它不会运行 submitComments() .

我试着做类似 $('#myModal').modal('hide'); 的事情, 但没有成功。

那么如何在 Angular 2 中关闭模态框呢?谢谢

<button type="button" class="btn btn-info" 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">
<form (ngSubmit)="submitComments()">
<div class="form-group row">
<label class="form-control-label col-sm-2">Comments:</label>
<div class="col-sm-10">
<textarea class="form-control" rows="3"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>

.

submitComments() {
// I want to do something like $('#myModal').modal('hide'); here.
}

最佳答案

使用@ViewChild

#closeBtn 添加到带有 data-dismiss="modal" 的元素中

<a><i class="fa fa-close" data-dismiss="modal" #closeBtn></i></a>

组件 html

<div class="modal fade" id="yourModalId">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<a><i class="fa fa-close" data-dismiss="modal" #closeBtn></i></a>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>

使用 this.closeBtn.nativeElement.click(); 触发点击事件将关闭您的模式。

组件 typescript

import {ViewChild, ElementRef} from '@angular/core';
@Component({
moduleId: ...,
selector: '.',
templateUrl: '.',
styleUrls: ['.']
})
export class yourClass {
@ViewChild('closeBtn') closeBtn: ElementRef;

yourFunction() {
//do something
...
...
//close your modal
this.closeModal();
}

//call this wherever you want to close modal
private closeModal(): void {
this.closeBtn.nativeElement.click();
}
}

关于angular - 如何关闭 Angular 2 中的模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35354041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com