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

Having trouble resolving all parameters for the service in an Angular2 test with Jasmine mocking

I am currently attempting to create a mock service for testing purposes: Production: @Injectable() export class UserService extends DtoService { // irrelevant details here. } @Injectable() export abstract class DtoService { constructor(private h ...

What are the best practices for utilizing the Express router efficiently?

When building a TypeScript REST API, is there any difference between router.get(); router.post(); router.patch(); router.delete(); ---------------- app.use(); app.use(); app.set(); and router .get() .post() .patch() .delete(); ---------- ...

Utilizing Angular RouterLink queryParamsHandling for managing optional parameters

Is there a proper way to combine the existing optional queryParams with an additional optional queryParam while linking in the template? Current URL: /search;brand=Trek Preferred link destination: /search;brand=Trek;start=1 (incrementing startCount) I a ...

When using TypeORM's save() method with an array of objects, the @PrimaryColumn() annotations are ignored, resulting

My current situation involves an entity called Point: @Entity() export class Point { @PrimaryGeneratedColumn('uuid') id: string; @IsUUID() @PrimaryColumn({ type: 'uuid', ...

Creating a FormGroup dynamically using an observable: A step-by-step guide

My current project involves creating a page with multiple reactive forms, tailored for different countries. These forms are generated based on JSON arrays received from the backend, allowing users to view and update settings individually. As I am uncertain ...

When attempting to asynchronously observe a datasource, the 'number' type cannot be assigned to the 'NgIterable<any>' type

I'm currently working with this simplistic component: import { Component, VERSION } from '@angular/core'; import { Observable, Observer } from 'rxjs'; @Component({ selector: 'my-app', templateUrl: './app.compone ...

An error has occurred: module @angular-devkit/build-angular/package.json could not be located

Whenever I try to run my project on VS Code, which has been working fine for others, I encounter this strange error that is beyond my understanding. Here is the screenshot of the error message: https://i.sstatic.net/xUBsZ.png It seems like there might be ...

The data type 'AbstractControl | null' cannot be assigned to type 'FormGroup'

I am facing an issue with passing the [formGroup] to child components in Angular. The error message says Type 'AbstractControl | null' is not assignable to type 'FormGroup'. I have double-checked my conditions and initialization, but I ...

Issue with tooltip not displaying attribute data-bs-title in Angular 17 with Bootstrap version 5.3

I am currently developing an Angular version 17 application and implementing a dynamic tooltip feature. The tooltip content will be supplied through a @Input() into the component. While a static tooltip works fine, I am facing an issue when trying to make ...

Obtaining information from an API using Angular

I am currently working on extracting data from various API's and I am encountering some difficulties. The initial part is functioning correctly, with the code provided below : ngOnInit(): void { this.http.get('http://.../api/getData?table=ge ...

Adjust the properties within the component's styles using Angular 2

In this project, the objective is to dynamically change the background-color based on different routes. The goal is to display a specific color for UpcomingComponent while keeping the background-color consistent for all other routes. The approach involves ...

Luxon DateTime TS Error: The 'DateTime' namespace cannot be used as a type in this context

I have encountered an issue while trying to set the type of a luxon 'DateTime' object in TypeScript. The error message DateTime: Cannot use namespace 'DateTime' as a type appears every time I attempt to assign DateTime as a type. Below ...

"Enhance user experience with Angular Material: Popup Windows that preserve functionality in the original window while staying vibrant and accessible

Exploring Angular Material Dialog and other Popup Window Components for a project. Making progress but facing some challenges. Here are the requirements: a) The original screen should not be grayed out, b) Users should be able to interact with the windo ...

Resolving the error message "Default props must have construct or call signatures for 'Component' in Typescript"

I'm currently working on a function component called MyComponent and I'm facing an issue with setting a default prop for component. The goal is to have the root node render as a "span" if no value is provided. However, I am encountering the follo ...

Step-by-step guide on filtering an array of objects using Vuejs and TypeScript

For this particular project, I am utilizing Vuejs Typescript with a data structure that looks like this: ["order": { "id":1, "created_at":"2019-12-06T10:22:17Z", "status":"open", ...

Guide on bringing in Javascript file into your Ionic/Angular application

Within my Ionic 2 application, I have incorporated three.js along with a PLYLoader extension for three.js (accessible here: https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/PLYLoader.js) Integrating three.js is straightforward by includi ...

Exporting constants using abstract classes in TypeScript files

In my Typescript files, I've been exporting constant variables like this: export const VALIDATION = { AMOUNT_MAX_VALUE: 100_000_000, AMOUNT_MIN_VALUE: 0, DESCRIPTION_MAX_LENGTH: 50, }; My constant files only contain this one export without any ...

Steps to activate a button once the input field has been completed

It's noticeable that the send offer button is currently disabled, I am looking to enable it only when both input fields are filled. Below, I have shared my code base with you. Please review the code and make necessary modifications on stackblitz 1. ...

Adjusting the size of the Knob in Ionic 5 upon pressing it

Is there a way to change the size of the knob in an "ion-range" element when it is pressed? I have checked the documentation, but could not find any information in the "ion-range" section. I would like to make this adjustment in SCSS: Normal Behavior Pre ...

Angular 8 httpClient experiencing asynchronous execution issues

I'm currently facing an issue where the order of execution within my WebService.webCall method seems to be incorrect. I am attempting to load content from files in an assets folder using Angular's HttpClientModule. Despite creating a stackblitz c ...