Having trouble with @viewChild not activating the modal popup and displaying an error message stating that triggerModal is not a function in

I am facing an issue where the click event is not being triggered from the parent component to display a Bootstrap 3 modal. I am getting the following error:

ERROR TypeError: this.target.triggerModal is not a function

This is what I have done so far:

Parent Component

@ViewChild('target') private target: ModalComponent;

ngOnInit(){
    this.target.triggerModal();
}

<button #target>Open Modal</button>

Modal Component

export class ModalComponent implements OnInit {     
    constructor() { }
    ngOnInit() {        

  }    
    triggerModal() {
        console.log('Model opened');
        $('#myModal').modal("show");
    }
}


<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Modal Header</h4>
            </div>
            <div class="modal-body">
                <p>Some text in the modal.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

Answer №1

To accomplish this, utilize the @ViewChild decorator in the following manner:

  @ViewChild(ModalComponent) modalC:ModalComponent; 
  parentButtonHandler(){
     this.modalC.triggerModal();
  }

Check out the live demonstration showcasing how to open a Modal of child component from the parent: demo

Answer №2

Given that target is of the type ModalComponent, it will look like this:

.html

<button (click)="openModal()">open modal</button>
<app-modal #target></app-modal>

.ts

@ViewChild('target') private target: ModalComponent;

openModal(){
  this.target.triggerModal();
}

Answer №3

After some troubleshooting, I managed to resolve the problem and documented the solution on StackBlitz. Hopefully, this can help someone else encountering a similar issue in the future.

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

Does the value of an Angular reactive form control only reflect what the user inputs?

I am working with a reactive form where I need to extract values and assign them to a variable defined in an interface. The form is populated using the Google Places API, which disables user interaction with all controls except for the initial address inpu ...

Utilizing a loaded variable containing data from an external API request within the useEffect() hook of a React component

Essentially, I have an API request within the useEffect() hook to fetch all "notebooks" before the page renders, allowing me to display them. useEffect(() => { getIdToken().then((idToken) => { const data = getAllNotebooks(idToken); ...

How can I access the directive model value in its primary controller within an Angular2 application?

I am working on a person page that utilizes a custom directive. <person-directive *ngFor="let person of persons; #idx = index" (remove) = "removePerson(idx)"> </person-directive> The person directive includes input fields as shown bel ...

Preview of Azure AD Consent Scopes and Access Token Version Error in Msal Angular

Currently in the process of updating my web application with the new MSAL library, @azure/msal-angular, from previously using the old ADAL library. The frontend of the web app is built with Angular 5 and communicates with a backend ASP.NET Core Web API. ...

Angular's Dynamic Reactive Forms

I encountered an issue while using Typed Reactive Forms in Angular 14. I have defined a type that connects a model to a strict form group. The problem arises specifically when utilizing the Date or Blob type. Note: I am working with Angular 14. Error: src/ ...

Modify a single parameter of an element in a Map

Imagine I have a map data type exampleMap: Map<string, any> The key in the map is always a string, and the corresponding value is an object. This object might look like this: { name: 'sampleName', age: 30} Now, let's say the user se ...

When starting a new project with Angular 7, the option to set up routing is automatically included without asking for confirmation

After switching from Angular 6 to version 7, I encountered an issue while creating a new project in CLI using ng new [app-name]. It simply starts without giving me the option to include routing or styling in my project. Just a heads up, I am currently run ...

Using Ionic to invoke a function within another function in a JavaScript service

Hey everyone, I've come across an issue while working on my Ionic mobile app project. I need to call a function within another function in one of my service.js files (pushNotificationService.js). Here is the code snippet: checkForNewMessage: functi ...

Issue deploying Angular 2 and Rails 5 on Heroku: npm command not found in bash

After successfully deploying an Angular2 on Rails5 app to Heroku and setting up the PG database, I encountered a stack trace in the Heroku app log indicating that the npm command was not found. This error has been perplexing as I try to troubleshoot the is ...

Error: Attempted to call the 'post' method on an undefined object, resulting in an Uncaught TypeError. This occurred within the Ionic 2 framework while executing the Javascript code located

While I attempt to convey my message in English, unfortunately, it is not a language I am fluent in. Currently, I am working on an Ionic 2 project. In this particular scenario, I am trying to make an HTTP request using the POST method while emulating it o ...

Limiting the image width of ngx-image-cropper to the popup container dimensions

I am currently working with a popup that contains an image cropper using ngx-image-cropper (https://www.npmjs.com/package/ngx-image-cropper) <div mat-dialog-container> <image-cropper [imageBase64]="imageFile" [mainta ...

What is the best way to access object IDs from Firebase and then save them individually?

I'm currently developing an Ionic application using the Angular framework. In order to remove objects from Firebase's real-time database, I need the ID of each object. Despite being a beginner in this field, I have not been able to find a solutio ...

Exploring Objects using Typescript

I need help creating a mapper for objects that allows TypeScript to recognize the returned type correctly. For example: type ExampleObject = { text: string; // this object may have properties of any type number: number; }; const object: ExampleObjec ...

Enhancing the efficiency of a TypeScript-written file content parsing class

Seeking advice on optimizing a typescript module used by a VSCode extension. This module accepts a directory and parses the content within the files, which can be time-consuming for directories with a large number of files. To avoid copying the entire cla ...

Should we use fakeAsync() or done() to handle asynchronous tasks

When creating an Angular test with Jest and dealing with asynchronous operations, do you have a preference for how to handle it? it('', fakeAsync(() => { // test code here })); or would you rather use something like it('' ...

Angular Material's <mat-select> tag allows for the inclusion of an <input> element within it

I am attempting to place an input element inside the mat-select tag of the Angular Material element. However, I am facing an issue where I cannot input any text into the input field inside the select element. Below is the code I am using to search for elem ...

Building a Secure User Service in Angular

Struggling to develop a security service for my Angular app, I encountered an issue with repetitive calls to the back-end API (which determines user permissions). Ideally, I want this call to happen once and other requests to piggy-back on that initial req ...

Are there any methods to utilize Zod for validating that a number contains a maximum of two decimal places?

How can I ensure that a numeric property in my object has only up to 2 decimal digits? For example: 1 // acceptable 1.1 // acceptable 1.11 // acceptable 1.111 // not acceptable Is there a method to achieve this? I checked Zod's documentation and sea ...

What is the correct way to invoke a static TypeScript class function in JavaScript?

Recently, I encountered a scenario where I have a TypeScript script called test.ts structured like this: class Foo { public static bar() { console.log("test"); } } The requirement was to call this TypeScript function from plain JavaScript ...

Utilizing const as the iteration variable in a for loop

I've grasped the concept of using var and let in a for loop in typescript/javascript, but can someone shed light on how and why a const variable as a loop variable behaves? for (const i = 0; i < 5; i++) { setTimeout(function() { console.log( ...