Executing a child component function once the parent component data is loaded in Angular 5

In my project, I have a parent component called program-page.component where I am invoking a function to fetch some data.

ngOnInit() {
this.getProgress();
}

getFirstProgramItem() {
   this._contentfulService.getProgramItem(4, 1)
    .then((programItem) => {
     this.programItem = programItem;
   }).then(() => {
     console.log(this.programItem);
   });
}

getProgress() {
this._trackingService.getLastItemProgress()
  .subscribe((result) => {
    this.progress = result;
    if (this.progress.sysID == null || undefined) {
      this.getFirstProgramItem();
    }
  });
}

Then, in my program-page.component.html

<app-program-header></app-program-header>
<app-week-display></app-week-display>
<app-program-item [item]="programItem"></app-program-item>

I am passing the programItem data, and in my program-item.component.ts file, I am retrieving and populating the data.

import { Component, OnInit, AfterViewInit, OnDestroy, Input } from '@angular/core';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { Entry } from 'contentful';
import { ContentfulService } from '../../../contentful.service';

declare var Player: any;
declare var Vimeo: any;

@Component({
  selector: 'app-program-item',
  templateUrl: './program-item.component.html',
  styleUrls: ['./program-item.component.scss']
})
export class ProgramItemComponent implements OnInit {

@Input() item: Entry<any>;

constructor(
    private contentfulService: ContentfulService
) { }

ngOnInit() {} 

loadVideo() {
   const video = new Vimeo.Player('video');
}

program-item.component.html

<div class="program-item">
<div class="main">
    <p *ngIf="item?.fields.asset[0].fields.textBlock" class="program-item_textblock">{{item?.fields.asset[0].fields.textBlock}}</p>
    <div id="video-panel">
      <div *ngIf="item?.fields.asset[0].fields.vimeoId" [attr.data-vimeo-id]="item?.fields.asset[0].fields.vimeoId" data-vimeo-responsive="1" id="video"></div>
    </div>
  </div>
</div>

What I am aiming for is to trigger the loadVideo() function after the data has been loaded.

I attempted using ngAfterContentInit, but it did not yield the desired results.

Any assistance on this matter would be greatly appreciated.

Thank you

Answer №1

It is important to note that the ngAfterContentInit function is triggered whenever the content on your page or component changes. If this function is defined in the parent component, it will be called every time there is a tick or click event in the application. However, this may not be the most efficient way to interact with child components.

There are two recommended approaches to interact with child components:

  • Utilize an EventEmitter
  • Use @ViewChild

1) If you need to access data from the child component in the parent component, consider using an EventEmitter. Here are some helpful resources on this topic:

Guide to Angular EventEmitter

Communicating with Nested Components in Angular

2) If you simply want to call a method in the child component from the parent component, you can use @ViewChild as shown below:

@ViewChild(ChildComponent) child: ChildComponent;
this.child.someMethod();

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

Is jQuery Autocomplete functioning properly on outdated browsers, but not on newer ones?

Here is the JSON data I have for my auto complete feature { "list" : [ { "genericIndicatorId" : 100, "isActive" : false, "maxValue" : null, "minValue" : null, "modificationDate" : 1283904000000, "monotone" : 1, "name":"Abbau", ...

Exploring Karma and Jasmine for Testing Angular Controllers Module

In an attempt to test my application, I have each controller defined in its own module rather than as a controller of the main app module, and then loaded as a dependency of the main app module. While running a test to check if the loginController is defin ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

Ways to incorporate customizable text and images into three.js

Recently, I've been experimenting with adding new images and text as textures to a 3D object using fabric js for my 3D configurator. My codebase is inspired by this GitHub repository, and I'm also utilizing this code from CodePen. One key aspect ...

Storing and retrieving text in a file using JavaScript: A step-by-step guide

I have a command set up where if a user is mentioned, the discord bot will save the mentioned user's name in a file (I'm utilizing discord.js and node.js). Below is my code snippet: const prv = require('C:/Users/Kikkiu/Desktop/prova.txt&apo ...

Tips for elegantly merging two Observables within an RXJS pipeline

I am working on developing a log viewer using Angular. Upon user entry, I aim to load historical logs and also begin monitoring for new logs. Users have the ability to filter logs using a simple form that emits a query object. Each time the query changes, ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...

Changing the URI in accordance with the previous URI

I am encountering an issue in my React application where multiple updates of the URI are being made within the same event by adding query parameters using the router.push function from various locations in the code. However, some updates are getting lost b ...

Forward users to specific date and time on Everwebinar link

Is there a way to automatically redirect visitors of my custom Everwebinar confirmation page (on my domain) to a specific URL at a set date and time that is included in the confirmation page URL? Here is an example of what the confirmation page URL looks ...

Having trouble inputting text into input field using ReactJS

I am currently facing a challenge while attempting to modify the value of an input field using ReactJS. The issue I am encountering is the inability to input values into the field. After reviewing several other queries, it appears that simply changing the ...

The parameter is causing the Aggregate Function to malfunction

When fetching MongoDB data, I encountered an issue. Using the JavaScript parameter to retrieve data from MongoDB resulted in a null return, but manually typing it brought all the data without any problems. That part is working fine. const data = await Numb ...

Potential issue with Jhipster: loading of data could be experiencing delays

I've encountered an issue with getting my chart to display properly. I am working on creating a chart using ng2-charts, where I retrieve data from a service and then display it on the chart. The problem arises when the data is not correctly displayed ...

Using Node.js, is there a way to divide an object's array property by 100 and then store each portion in individual files?

Looking to break down a large object into chunks of 100 and save each chunk in separate files using Node.js. However, struggling to figure out how to split an array with thousands of records into files of 100. Query: How can I divide an object's arr ...

What is the best approach to alter a user's message depending on the form's ID that was used for submission?

I currently have two separate screens that each serve a specific purpose, where only one can be open at any given time. First is the login form: <form action="/Account/Login" id="login-form" class="form" method="post"> <butto ...

Is it possible to access prop properties within the ready() function?

I am seeing the error message undefined in the console, specifically originating from the ready() function. The issue I am encountering is related to attempting to assign the value of this.users.name to this.userForm.name. Can someone please point out wh ...

Limiting character count in jQuery using JSON

I am trying to manipulate the output of a snippet of code in my jQuery: <li> Speed MPH: ' + val.speed_mph + '</li>\ that is being pulled from a JSON endpoint and currently displays as: Speed MPH: 7.671862999999999 Is there a ...

Increase the number of button groups when clicked

I have a button group with three buttons: left, middle, and right. I want to enhance this functionality so that when any of the main buttons are clicked, the corresponding sub-buttons (left-sub, middle-sub, or right-sub) appear accordingly: <div class= ...

Automatically Populate list upon webpage initialization - React, Redux, Firebase

A webpage I am working on consists of two main components: Categories and Items By utilizing the function initCategories() called within the componentDidMount() lifecycle method of Categories, I successfully display all categories on the screen. The initC ...

Issue encountered while sending binary data to the server

After attempting to read a local file on the client side and sending it to the server, I encountered an error while trying to retrieve the image. JavaScript let req let rsp async function _post(url,data) { req = await fetch(url,{method: 'POST' ...

I am looking to personalize the AddedToCartDialogComponent with the selector cx-added-to-cart-dialog

I've been trying to tailor the AddedToCartDialogComponent by incorporating new elements into the dialog window. Despite closely following Spartacus documentation, I am unable to see any changes taking effect. Running on Spartacus version 4, here is a ...