[英]How can i open a modal in angular 7 without using a button click,
如何在不使用按鈕單擊的情況下以 angular 7 打開模態。 當我在不使用按鈕單擊的情況下從其中一個 API 獲得響應時,我需要打開一個模式。 我是 angular 的新手。 我的 HTML :
<ng-template #Qpaper let-c="close" let-d="dismiss">
<div class="modal-header text-white" >
<div class="modal-title " id="modal-basic-title" >
<h4>Draft Selected Question</h4>
</div>
<button type="button" class="close text-white" aria-label="Close" (click)="d('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body p-0">
<p>q paper preview </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" (click)="d('Cross click')">Cancel</button>
</div>
我嘗試過以下代碼來觸發模態事件:
this.modalService.open('Qpaper');
this.modalService.open(data.response , Qpaper)
你可以看到這個例子https://stackblitz.com/edit/angular-modal-service?file=app%2Fapp.component.ts
然后在AppComponent
調用onCreateModal()
沒有按鈕點擊你可以打開模態
您需要使用 View Child 並從模板中獲取引用。
@ViewChild('Qpaper') private qpaper;
不要忘記導入 ViewChild。
import { ViewChild } from '@angular/core';
最后你可以簡單地做到這一點
this.modalService.open(qpaper);
您可以將模態包裝在它自己的組件中。
我的modal.component.ts
import { Component, OnInit, Input } from '@angular/core';
import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-my-modal',
templateUrl: './my-modal.component.html',
styleUrls: ['./my-modal.component.css']
})
export class MyModalComponent implements OnInit {
@Input() response: any;
constructor() { }
ngOnInit() {
}
}
我的modal.component.html
<div class="modal-header text-white" >
<div class="modal-title " id="modal-basic-title" >
<h4>Draft Selected Question</h4>
</div>
<button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body p-0">
<p>q paper preview </p>
<p class="card-text">ID: {{ response.id }}</p>
<p class="card-text">Title: {{ response.title }}</p>
<p class="card-text">Value: {{ response.value }}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" (click)="activeModal.close('Close click')">Cancel</button>
</div>
然后它可以導入到父組件中並根據需要打開。 在您的情況下,來自 API 請求的有效響應。
父組件
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { MyModalComponent } from './my-modal/my-modal.component';
export class AppComponent implements OnInit {
constructor(private modalService: NgbModal) { }
ngOnInit() {
this._apiService.getDetails().subscribe(
response => {
this.openMyModal(response);
},
error => {
console.error('Unable to retrieve data from API: ', e);
}
);
}
openMyModal(response: any) {
const modalRef = this.modalService.open(MyModalComponent);
modalRef.componentInstance.response = response;
}
}
然后在收到來自 API 請求的有效響應時調用openMyModal()
函數。
這種方法的一個優點是,與任何其他組件一樣,它允許您在父組件中根據需要打開任意數量的模態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.