Executing a function in the constructor of an Angular4 component

I am currently facing an issue where I am attempting to invoke a modal function within the constructor in Angular 4. However, it seems that the function is not being called properly as it gets highlighted. Upon loading the page, no errors are logged and the modal does not appear as expected. While the screen darkens, the text inside the modal does not display.

constructor(public formBuilder: FormBuilder,
            public router: Router,
            public toastr: ToastrService,
            public http: HttpClient,
            public modalService: BsModalService,) {
  if (this.getWardData) {
    this.displayHint();
  }
}

displayHint(template: TemplateRef<any>) {
  this.modalRef = this.modalService.show(template, {class: 'modal-sm'});
}

HTML

<ng-template #template>
  <div class="modal-body text-center">
    <p>Do you want to Continue where you left?</p>
    <button type="button" class="btn btn-default" (click)="confirm()" >Yes</button>
    <button type="button" class="btn btn-primary" (click)="decline()" >No</button>
  </div>
</ng-template>

Answer №1

Here is a code snippet that you can utilize:

constructor(public formBuilder: FormBuilder,
    public router: Router,
    public toastr: ToastrService,
    public http: HttpClient,
    public modalService: BsModalService, ) {
    // if (this.getData) {
    //   this.showHint();
    // }
  }

  ngOnInit() {
    if (this.getData) {
      this.showHint();
    }
  }

  showHint(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template, { class: 'modal-sm' });
  }

Answer №2

It appears that there may be an issue with your modal template implementation. While you can initialize your modal, you must ensure to pass the template parameter (TemplateRef) to the displayHint method. In your view, it seems like you have the necessary template but it lacks a reference in the component implementation. You should include the following code snippet in your component (to establish a reference to your modal template for displaying the modal):

@ViewChild('template') private modalTemplate: TemplateRef<any>;

You should remove this.displayHint() from your constructor and instead add ngAfterViewInit within the ngOnInit implementation. Inside the ngAfterViewInit method, make sure to call the displayHint method:

export class YourComponentName implements AfterViewInit {
    @ViewChild('template') private modalTemplate: TemplateRef<any>;

    getWardData = true;

    constructor(public formBuilder: FormBuilder,
                public router: Router,
                public toastr: ToastrService,
                public http: HttpClient,
                public modalService: BsModalService
    ) {}

    ngAfterViewInit() {
        if (this.getWardData) {
            this.displayHint(this.modalTemplate);
        }
    }

    displayHint(template: TemplateRef<any>) {
      this.modalRef = this.modalService.show(template, {class: 'modal-sm'});
    }
}

It is crucial to understand the distinction between the constructor and the ngOnInit/ngAfterViewInit methods of a component in Angular. The Angular bootstrapping process involves two main stages:

  • Constructing the components tree
  • Running change detection

The controller method executes during the "Constructing components tree" stage.

(The reference to the modal template is undefined at this point)

Your ngOnInit method runs during the "Running change detection" stage.

(The reference to the modal template is defined here)

The @Input communication mechanism is processed during the subsequent change detection phase, hence input bindings are not accessible in the constructor.

Therefore, running your modal from the constructor is not feasible.

For more information on lifecycle hooks, refer to this link

You can access a live working example here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There was an issue encountered while trying to use HTTPS with a self-signed certificate from a

I made the switch to using https for my nodejs server by following these steps: const https = require('https'); const privateKey = fs.readFileSync('sslcert/server.key', 'utf8'); const certificate = fs.readFileSync('sslc ...

Identifying whether a particular area is represented in a geographic map array presents a significant challenge

Having an issue with typescript currently. I have a variable that contains different string entries representing x, y positions. The entries are as follows: ["3,3","3,4","3,5","2,3","2,4","2,5","-1,-2","-2,- 2","-2,-1"] My goal is to determine if this land ...

Angular 4 - Resolve ngModelChange Error: Property '...'is Undefined When Binding Two Select Form

I need assistance with implementing a functionality in Angular 4. I have a JSON model that contains information about books, including their titles and authors. I want to create two select form elements (dropdowns): the first dropdown should display the ti ...

Using React hooks with Material-UI: Snackbar displaying only on first occasion and not again

I have identified an issue that can be easily reproduced. Steps to replicate: Step 1: Start a react app and include material-ui in the project: prompt> create-react-app mui-test prompt> cd mui-test prompt> yarn add @material-ui/core @material-ui ...

Angular request: HTTP request<any> is not generic

Struggling with creating an error interceptor service in Angular. Having trouble instantiating a HttpRequest. New to Angular and Web App development. Here is my code snippet: import { Injectable } from '@angular/core'; import { HttpInterceptor ...

Tips for adjusting the item count in mat-autocomplete

For quite some time now, I've been attempting to adjust the number of items in a mat-autocomplete without any luck. My project involves using material.angular.io Below is a snippet of my code import { Component, OnInit } from '@angular/core&a ...

Tips for including a sequelize getter in a model instance?

I'm currently struggling to add a getter to the name field of the Company model object in my project. Despite trying various approaches, I haven't had any success so far. Unfortunately, I also couldn't find a suitable example to guide me thr ...

Angular Email Validator triggers inconsistently based on conditions

I am working on validating email addresses only when they are provided. My approach involves subscribing to the valueChanges function and applying validators based on certain conditions. However, I have encountered an issue where the validator does not tri ...

The problem of parameter being NULL in a post request in a .Net Core 3.0 Angular application

This is my first venture into the world of .Net Core Angular projects, so I apologize if my question appears to be too basic. Despite researching similar issues, I am still unable to resolve my problem, which leads me to believe that I must be making a mis ...

Incorporate playerVars options into your Angular application with the help of @angular/youtube-player package

I am currently using the @angular/youtube-player to display a video within my Angular application. I want the video to play automatically upon loading. After reviewing the documentation, I found the necessary parameters to enable autoplay, but for some re ...

I encountered difficulties connecting mongoose to my local MongoDB server

Hello Everyone! Currently, I am in the process of linking my node.js project to mongodb. Initially, everything worked smoothly when I used mongodb atlas. However, when I attempted to connect it using mongodb compass, I faced some issues and nothing seemed ...

Dealing with problems related to types in React and TypeScript createContext

Struggling to pass the todos (initial state) and addNewTodo (methods) using React Context hook and typescript. Despite trying multiple solutions, errors persist. Partial generics do not cause issues in the context component, but I encounter the error Cann ...

A more effective strategy for avoiding the use of directives or jQuery in AngularJS

I need guidance on using Angular directives, especially when deciding between JQuery and Angular 1 directives for a particular scenario. Here is an example of my object list: [ { "id":"sdf34fsf345gdfg", "name":"samson", "phone":"9876543210", ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

What steps are involved in setting up a SAML service provider using @node-saml/node-saml?

I'm currently working on a SAML SP implementation using the @node-saml/node-saml library. Despite creating the necessary source code, I am facing an issue with the SAML authentication not functioning as expected. Can anyone provide guidance on how to ...

Tips for ensuring that jQuery runs in the correct order within Angular 2

As a beginner with Angular 2 and asynchronous loading, I have encountered some difficulties in finding the right approach for running jQuery scripts in the correct sequence within an Angular 2 project. Despite exploring various resources such as: How to u ...

Tips for managing the data type of a bound value through ngModel: preventing number distortion to string

I posted a query and managed to solve it. However, I observed that even though the provided data consists of objects defined like this: export interface GisPoint { e: number; n: number; } when a user inputs a value, the original content changes from { e: ...

Infragistics: A guide to displaying numerous ignite Snackbar instances with unique identifiers

I am trying to display multiple Snackbars on my Angular website. I'm utilizing Ignite UI for Angular and incorporating the Snackbar feature from Ignite. <igx-snackbar id="snackbar1" [displayTime]="displayTime"> <div [cla ...

Adding an entry to a dictionary in a TypeScript file

I'm trying to filter a dictionary in Angular, but I'm having trouble inserting the selected items into my final dictionary. Can anyone help me with this issue? Thank you. filterData(data: any): any{ for (var x = 0; x < data.length; x++){ ...

Encountering memory leaks and displaying repetitive data due to having two distinct observables connected to the same Firestore

I am currently utilizing @angular/fire to retrieve data from firestore. I have two components - one serving as the parent and the other as the child. Both of these components are subscribing to different observables using async pipes, although they are bas ...