Executing functions from a child component in a parent component in Angular 2

I'm currently working on ng2 RC6. I have a parent component and a child component.

Within the child component, I am utilizing an ng2-bootstrap modal and the following start function:

import { Component, ViewChild, AfterViewInit, Input } from '@angular/core';
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';

@Component({
    selector: 'nba-form',
    templateUrl: './form.component.html'
})


export class FormComponent {
    public modal:boolean = false;

    @ViewChild('childModal') public childModal: ModalDirective;
    @ViewChild('lgModal') public lgModal: ModalDirective;

    public showChildModal(): void {
        this.childModal.show();
    }

    public hideChildModal(): void {
        this.childModal.hide();
    }

    ngAfterViewInit() {
        this.lgModal.show();
    }
}

In the parent component, I would like to call the function "this.lgModal.show()", which opens the modal window.

{...}
import { FormComponent } from './form.component';
import 'rxjs/add/operator/toPromise';

@Component({
    selector: 'nba',
    templateUrl: './nba.component.html',
    providers: [FormComponent]
})
export class NbaComponent implements OnInit {

    constructor(private appService: AppService, private formComponent: FormComponent) {}

However, when I use:

ngOnInit() {
    this.formComponent.lgModal.show();
}

I receive an error stating that show(); is undefined.

Here is the snippet of code from app.module.ts:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { HttpModule, JsonpModule }    from '@angular/http';

import { ModalModule } from 'ng2-bootstrap/ng2-bootstrap';
import { AlertModule, DatepickerModule } from 'ng2-bootstrap/ng2-bootstrap';

// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular2-in-memory-web-api';
import { InMemoryData } from './in-memory-data';

import { FormComponent } from './form.component';
import { NbaComponent } from './nba.component';
import { AppComponent }   from './app.component';
import { AppService } from './app.service';
import { routing } from './app.routing';

@NgModule({
  imports: [
    BrowserModule,
    AlertModule,
    FormsModule,
    HttpModule,
    DatepickerModule,
    InMemoryWebApiModule.forRoot(InMemoryData),
    ModalModule,
    routing
  ],
  declarations: [AppComponent, NbaComponent, FormComponent],
  providers: [AppService],
  bootstrap: [AppComponent]
})

export class AppModule {

}

PS. I am able to open the modal from the child component successfully, but encountering issues when trying to do so from the parent component. Any hints or solutions would be greatly appreciated! :)

Regards, Bosper

Answer №1

I successfully resolved this issue by including an instance of the child component within the parent component using an annotation called @ViewChild(). This way, I was able to execute a function from the child component:

@ViewChild(FormComponent)
    private formComponent: FormComponent;

    ngAfterViewInit() {
        this.formComponent.lgModal.show();
    }

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

The issue arises when attempting to apply CSS styles to an existing component or body tag,

I am currently working on an Angular 7 project where I have a requirement to dynamically load a component using routes. However, when I try to add styles for the body tag and existing component tags in the dynamically loaded component style-sheet, they do ...

How to access an element through the router-outlet in Angular 6?

<side-navigation [navigationTitle]="navTitle"></side-navigation> <router-outlet> </router-outlet> Within my project, I have a navigation bar located in the root component. I have set up [navigationTitle] as an @Input Decorator wit ...

Is there a way to verify if a component contains a child node with the tag <template></template>?

Consider the scenario with MyComponent: <div [my-component]="'text'"></div> Within the code, I have access to this.viewContainerRef, which refers to the DOM node itself (<div>). However, for customization purposes, a user mig ...

Insert an HTML element or Angular component dynamically when a specific function is called in an Angular application

Currently, I am working on a component that contains a button connected to a function in the .ts file. My goal is to have this function add an HTML element or make it visible when the button is clicked. Specifically, I would like a dynamic <div> elem ...

Angular 2 mistakenly utilizing incorrect RouterOutlet

I'm facing an issue with implementing md-tabs along with the router-outlet to avoid preloading all data at once. My goal is to load data only when needed. AdminComponent.html <a [routerLink]="['categories']"><h1>to categories&l ...

What is the prescribed interface or datatype for symbol type in TypeScript with JavaScript?

I have a set of symbol values in JavaScript that I want to convert to TypeScript. // Defining object values in JavaScript const size = { Large: Symbol('large'), Medium: Symbol('medium') } What is the most efficient method to conv ...

Ensuring TypeORM thoroughly examines all columns with the decorators in NestJS

Is there a method to ensure the uniqueness validator in the TypeORM entity inspects all columns and provides notifications for all detected errors collectively? Consider this schema as an example: import { BaseEntity, Column, Entity, PrimaryGenera ...

Angular2: Issue with service injection within service

Below is the code snippet I have written. Assuming you can grasp the purpose without further elaboration. @Injectable() export class Dispatcher { } @Injectable() export class TodoStore { constructor(@Inject(Dispatcher) private dispatcher:Dispatcher ...

React: Unable to locate an index signature with a parameter of type 'string' on type N

While working with a React component, I encountered an issue when trying to access a property from my component state using a key. My editor showed the following warning: Element implicitly has an 'any' type because expression of type 'str ...

Angular 6: A guide to dynamically highlighting navbar elements based on scroll position

I am currently building a single page using Angular 6. The page is quite basic, and my goal is to emphasize the navbar based on scrolling. Below is the code snippet I am working with: .sticky { position: sticky; top: 0; } #i ul { list-style-type: ...

Retrieving selected dropdown list value using Angular 2

So, I have this database table with two attributes - Name_of_Game and Type_of_Game. I've managed to extract the Name_of_Game into a select dropdown list. But now, my goal is to automatically set the type input to the game's respective type after ...

Unspecified parameter for Next.js dynamic route

Currently, I am developing an e-commerce application using next.js with Typescript and MongoDB. To better understand my project, let's take a look at my existing file structure: https://i.stack.imgur.com/tZqVm.png The mainPage.tsx file is responsibl ...

Encountering the 'Default setting for timestampsInSnapshots now set to true' error in Firestore console

Encountering a Firestore error in the console while using Angular. @firebase/firestore: Firestore (5.8.3): The timestampsInSnapshots setting now defaults to true and does not require explicit setting. It is advised to remove it from firestore.settings( ...

Value attribute property binding

Currently, I am diving into the world of Angular 5 and focusing on grasping the fundamentals. One concept that caught my attention is template reference variables. However, I encountered a roadblock along the way. Instead of utilizing a template reference ...

Incorporate FontAwesome icons into table headers within an Angular framework

I am attempting to customize the icons for sorting in my table headers by following the guidelines laid out in the ng-bootstrap table tutorial. The NgbdSortableHeader directive plays a key role in changing the sorting of columns: @Directive({ selector: ...

Ionic3 footer using ion-tabs

Is there a way to create a common footer for all pages with 5 buttons, where the first button is selected by default? The page opened by this first button should have three tabs. I have already created the tabs but am unsure how to add the footer without r ...

Here is a step-by-step guide on creating a custom select all checkbox in the toolbar of a MUI

I am currently using the MUI data grid to build my table, with the following properties: <DataGrid rows={serialsList || []} columns={columns} rowsPerPageOptions={[25, 50, 100]} //pageSize={93} ...

Assign variable data to properties within an immutable object within a React component

I have declared a Const in my config.service.ts file like this: export const mysettings={ userid:"12324", conf:{ sessionDuration:30, mac:"LON124" } } I am using this constant in various components. However, instead of hardcoding these val ...

The HTML template remains unchanged unless explicitly triggering detectChanges() with change detection set to onpush

In my Angular component, I am utilizing change detection on push. The component includes an input that gets modified by the component when the route changes. However, I noticed that simply assigning a new reference to the input and making modifications d ...

Downloading a CSV file using Angular 8 and Django RestFramework

I am a beginner in Angular and I'm looking to implement a feature where users can download a CSV file upon clicking a download button. Django viewset @action(detail=False, methods=['get']) def download_csv(self, request): data = { ...