如何在不单击按钮的情况下以角度7打开模态。当我从API之一获得响应而不使用按钮单击时,我需要打开一个模式。我是新来的角度。我的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
然后在不单击按钮的情况下调用onCreateModal()
中的AppComponent
,您可以打开模态
您需要使用View Child并从模板中获取引用。
@ViewChild('Qpaper') private qpaper;
不要忘记导入ViewChild。
import { ViewChild } from '@angular/core';
最后您可以简单地做到这一点
this.modalService.open(qpaper);
您可以将模式包装在它自己的组件中。
my-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() {
}
}
my-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()
函数。
此方法的一个优点是,与其他任何组件一样,它允许您在父组件中打开所需数量的模态。