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

How can I arrange selected options at the top in MUI autocomplete?

I am currently working with mui's useAutocomplete hook https://mui.com/material-ui/react-autocomplete/#useautocomplete Is there a way to programmatically sort options and place the selected option at the top using JavaScript sorting, without resorti ...

Guide to executing Jest tests with code coverage for a single file

Instead of seeing coverage reports for all files in the application, I only want to focus on one file that I am currently working on. The overwhelming nature of sifting through a full table of coverage for every file makes it difficult to pinpoint the spe ...

List the attributes that have different values

One of the functions I currently have incorporates lodash to compare two objects and determine if they are identical. private checkForChanges(): boolean { if (_.isEqual(this.definitionDetails, this.originalDetails) === true) { return false; ...

The OR operator in TypeORM allows for more flexibility in querying multiple conditions

Is there any OR operator in TypeORM that I missed in the documentation or source code? I'm attempting to conduct a simple search using a repository. db.getRepository(MyModel).find({ name : "john", lastName: "doe" }) I am awar ...

react-router: The 'history' type is not found in the current context

Here is some code snippet from App.tsx: interface AppProps{ history: any } export default class App extends React.Component<AppProps,...> { public state = { target: this.props.history.push('/') }; private route() { if (! ...

Securely transfer data between objects using a for loop

Description I have two similar types that are not identical: type A = { a?: number b?: string c?: boolean } type B = { a?: number b?: string c?: string } I am looking to create an adapter function f() that can convert type A to type B, with ...

Guide to sending client-to-client notifications in Angular/Ionic with Firebase Cloud Messaging

I am looking to implement client-client push notifications (not server-to-client). My goal is to send a notification when one user messages another. Is this feasible? How can I achieve this using the structure in the Firebase real-time database? Here is a ...

When trying to update a form field, the result may be an

Below is the code for my component: this.participantForm = this.fb.group({ occupation: [null], consent : new FormGroup({ consentBy: new FormControl(''), consentDate: new FormControl(new Date()) }) }) This is th ...

What causes a slow disappearance of both the form element and its child elements when the visibility attribute is set to hidden on the

Have you ever noticed that the child elements of an element form hide slowly when using visibility:hidden, but hide quickly when using display:none? This slow hiding can negatively impact user experience. I tried to find information on this issue, but eve ...

Appending or removing a row in the P-Table will result in updates to the JSON

My task involves implementing CRUD (Create, Read, Update, Delete) functionality for my table. While Create, Read, and Update are working fine with the JSON file, I am struggling to figure out how to delete a specific row in the table without using JQuery o ...

Ways to dynamically update the state of a mat-button-toggle-group programmatically

I'm currently working on implementing a confirmation dialog to change the state of MatButtonToggleGroup. However, I am facing an issue where I need to prevent the default behavior unless I revert to the previous state upon cancellation. Here's t ...

What is the correct way to utilize a variable as a parameter in React Query while employing the axios.request(options) method?

I'm currently working on a React Query component with the following structure: function test () { const [var, setVar] = useState("") const options = { method: "GET", url: "https://api.themoviedb.org/3/search/tv" ...

Angular: Resetting a conditional form control with matching name

Currently, my code looks something like this: <input *ngIf="a" #autocomplete formControl="myControl"> <input *ngIf="!a" #autocomplete formControl="myControl"> These inputs have different attributes depen ...

Display JSX using the material-ui Button component when it is clicked

When I click on a material-ui button, I'm attempting to render JSX. Despite logging to the console when clicking, none of the JSX is being displayed. interface TileProps { address?: string; } const renderDisplayer = (address: string) => { ...

Techniques for importing esm libraries without requiring the "type": "module" declaration in the package.json configuration file

I have successfully implemented a TypeScript Node project but now I am facing an issue while trying to integrate the VineJS library into the project. The problem arises because VineJS is exclusively an ESM (ECMAScript Module) package, and when adding it to ...

Having difficulty in using pipe to filter records upon clicking the Button

I am having trouble filtering the records as needed. What I want is that when "All" is clicked, no filter should be applied. When any other option is clicked, the filter should be applied. HTML <div class="container " style="padding-top:100px"> ...

What is the best way to access form data in React using a React.FormEvent<HTMLFormElement>?

I am looking for a way to retrieve the values entered in a <form> element when a user submits the form. I want to avoid using an onChange listener and storing the values in the state. Is there a different approach I can take? login.tsx ... interfa ...

Transmitting JSON and FormData between Angular and Spring

Angular Tutorial processRegistration(user: any, file: File): Observable<any>{ let formData = new FormData(); formData.append("user", JSON.stringify({username:'User'})); formData.append("file", file); return this. ...

Communicating between different components in Angular 11 using a service to share data

In my Angular 11 project, componentB has multiple methods that need to be called from componentA. Although I am aware that transferring these methods to a service would be the proper solution, it requires extensive effort which I want to avoid for now. In ...

An issue arises in Typescript when attempting to pass an extra prop through the server action function in the useForm

I am struggling with integrating Next.js server actions with useFormState (to display input errors on the client side) and Typescript. As per their official documentation here, they recommend adding a new prop to the server action function like this: expo ...