I am trying to open an ngx Modal window after an http call made from an angular application.
Here is the code of app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ModalModule } from 'ngx-bootstrap/modal';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
ReactiveFormsModule,
BrowserAnimationsModule,
ModalModule.forRoot(),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Here is the code of the component in which the http call is made
import { Component, TemplateRef, ViewChild } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Tour } from './Models/Tour/tour.model';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'AnguLearn';
public fGroup: FormGroup;
public Tours : Tour[] = [];
public Empty = false;
@ViewChild('template', {static: true}) modalr? : TemplateRef<any>;
modalRef?: BsModalRef;
constructor(private modalService: BsModalService){
}
public getDatas(){
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8'
})
};
this.http.post<[Tour]>("https://localhost:44387/api/tours", filter_details, httpOptions).subscribe(
(response)=>{
this.Tours = response;
this.Empty = response.length <= 0;
this.openModal(this.modalr);//I want to open a modal box here
}, errors=>{ console.log(errors)});
}
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template);
}
}
It did not work, and it did not compile. I always get the following error on the line with this.openModal(this.modalr);
:
Argument of type 'TemplateRef | undefined' is not assignable to parameter of type 'TemplateRef'. Type 'undefined' is not assignable to type 'TemplateRef'.
Any idea?
CodePudding user response:
You have a type error here.
@ViewChild('template', {static: true}) modalr? : TemplateRef<any>;
?
means optional value for modalr
. If it's true, you should change your methods in this way of typing. Or if you sure to have value in TemplateRef
- just remove ?
sign from property syntax like that:
@ViewChild('template', {static: true}) modalr : TemplateRef<any>;
If you not sure you have template value do that:
openModal(template?: TemplateRef<any>) {
if (template) {
this.modalRef = this.modalService.show(template);
}
}