Can you explain the process for accessing a parent function in Angular?

I have a form component that inserts data into a database upon submission, and I need to update the displayed data in another component once it changes in the database. I attempted using ViewChild to invoke the necessary functions, but encountered issues with ViewChild being undefined after submission.

The DataComponent below is responsible for rendering the data on the HTML page:

export class DataComponent implements OnInit{  
      constructor(private dataService: DataService,private router:Router) {
            this.getData();
           }
        
          ngOnInit(): void {
          }
          getData(){
            this.dataService.getData().subscribe(
              resp => this.data = resp,
              error =>console.log(error)
            );
          }
          detail(id: number){
            this.router.navigate(['data/check' + id]);
          }
}

And CheckComponent serves as the form component:

export class CheckComponent implements OnInit,AfterViewInit {
      form: FormGroup;
      data: any = [];
      id: number;
      @ViewChildren(DataComponent) dataComponent: DataComponent ;
      constructor(
        private formBuilder: FormBuilder,
        private router: Router,
        private route: ActivatedRoute,
        private dataService: DataService
      ) {
         this.id = parseInt(this.route.snapshot.paramMap.get('id'));
          this.Service.getReporte(this.id).subscribe(
            (resp: any) => this.data = resp,
            (error) => console.log(error)
          );
        }
      }
      ngOnInit(): void {
        this.makeForm();
      }
     makeForm() {
        this.form = this.formBuilder.group({
          ...
        });
      }
    
    sendData() {
        const data = {
                  ...    
         };
          this.dataService.createData(data).subscribe(
            (resp) => console.log(resp),
            (error) => console.log(error)
          );
          this.dataComponent.getData(); //undefined
          this.router.navigate(['data']);
        }
    
      }

Is there an alternative method to call functions from another component instead of ViewChild? Have I implemented it incorrectly? I specifically need to access the getData() function from the DataComponent.

Answer №1

If DataComponent is a child of CheckComponent, it is advisable to implement a top-down approach or one-way data binding for the data flow. Follow these steps:

  • Keep track of the main data object in a property within CheckComponent.
  • Include an input on DataComponent that can receive the main data object.

When the data on CheckComponent is updated, change detection will take place. This update will be propagated DOWN to DataComponent, thereby automatically updating its view.

Using this method aligns with your intended goal and is the recommended approach.

Answer №2

When using ViewChildren, you are provided with a QueryList instead of a single instance of the component.</p>
<pre><code>import {QueryList} from '@angular/core';

...

ViewChildren(DataComponent) dataComponent: QueryList<DataComponent>;

The proper typing for this is as follows: QueryList. The API offers similar functions to the JavaScript array API, allowing you to perform actions like...

this.dataComponent.forEach(dc => dc.getData());

To learn more about the QueryList API, visit: https://angular.io/api/core/QueryList

On the other hand, ViewChild provides access to the first instance of the child component on the page:

ViewChild(DataComponent, {static: false}) dataComponent: DataComponent;

If you only have or want one instance of DataComponent and wish to access it, this method will suffice.

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

Cannon-js: Experience dynamic body bouncing on the y axis as it reacts to force applied on the x and z axes

Currently, I am working on an FPS game where the player controller applies force based on keyboard inputs to a dynamic cannon body. The angular dampening is set to 1 on the player body. The PlayerController class takes both the player class (which extends ...

Toggle the visibility of a modal in code across various components in an Angular 4 project using Typescript

As I was working on my university App, I encountered an issue while attempting to open a Bootstrap modal in code from a different component. Opening a component in code from the same component posed no problems for me as I use JQuery and it functions perfe ...

Angular 2 and TypeScript: Mastering Checkbox Data Binding

Below is the HTML view in which user roles are checked. I want to bind a table of modified user roles using the actualizeRoles() method. How can I achieve this? <md-accordion class="example-headers-align"> <md-expansion-panel hideToggle=" ...

Attempting to modify read-only properties is prohibited in strict mode within the context of [background: url({{XXX}}) no-repeat center center

I encountered an issue in Edge, but everything works fine in Chrome. I can't figure out what's causing the problem... <div class="container-fluid project_img" style="background: url({{_project.images.web}}) no-repeat center center;"> ...

Dissimilarities in behavior between Angular 2 AOT errors

While working on my angular 2 project with angular-cli, I am facing an issue. Locally, when I build it for production using ng build --prod --aot, there are no problems. However, when the project is built on the server, I encounter the following errors: . ...

The Angular2 Observable fails to be activated by the async pipe

Take a look at this simple code snippet using angular2/rxjs/typescript public rooms: Observable<Room[]>; constructor ( ... ) { this.rooms = this.inspectShipSubject .do(() => console.log('foo')) .switchMap(shi ...

Jest's --findRelatedTests fails to identify associated test cases

Whenever I execute the command jest --bail --findRelatedTests src/components/BannerSet/BannerSet.tsx , an unexpected message is displayed: I couldn't locate any tests and hence exiting with code 1 If you want to exit with code 0 even when there are n ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

Encountering issues with installing packages while creating a new Angular 9 project

Recently I updated to node version 12.16.1 (LTS) and Angular CLI version 9.0.3. After creating a new project with the CLI, all files in the root folder are generated but it gets stuck during the installation of node packages. Has anyone else encountered t ...

Build a Google Map Widget within SurveyJs

Hey there, I'm new to working with SurveyJS and I'm trying to incorporate a Google Map widget into my SurveyJS. I followed some steps and successfully added the map in the Survey Designer section, but unfortunately, it's not loading in the T ...

What could be causing my Angular 8 project to fail to start following the installation of Angular 10 CLI?

Previously, I was working on an Angular 8 project on my computer. However, I now need to install Angular 10 to run another project. To do so, I globally installed the new version with the following command: npm install -g @angular/cli After successfully ...

Translating SQL to Sequelize Syntax

I have an SQL query that I need to rewrite as a sequelize.js query in node.js. SELECT historyTable1.* FROM table1 historyTable1 WHERE NOT EXISTS ( SELECT * FROM table1 historyTable2 WHERE historyTable2.id=historyTable1.id AND historyTable2.da ...

Having trouble adding Bootstrap to Angular with Webpack? You might come across the error message: "File to import not found or unreadable: ../bootstrap/sc

I have decided to incorporate Bootstrap into my project. My attempt at installation involved using "bootstrap": "^4.0.0-alpha.5" I followed a tutorial found at https://github.com/AngularClass/angular2-webpack-starter/wiki/How-to-use-Bootstrap-4-and-Sass- ...

How to include a cancel button within a tab component using Angular Material

I recently implemented a tab component with custom label templates. You can view the code and see how it works in this StackBlitz project. My question is, how can I add a cancel button to the top-right corner of the tabs? I don't need the button to do ...

Utilize mapping for discriminated union type narrowing instead of switch statements

My objective is to utilize an object for rendering a React component based on a data type property. I am exploring ways to avoid utilizing switch cases when narrowing a discriminated union type in TypeScript. The typical method involves using if-else or sw ...

In an Angular component, attempt to retrieve the data type of a class property

Discover how to retrieve the type of properties from an object by following this Typescript tutorial link. However, it seems to be behaving like Javascript and returning the value of the property instead of the type: const x = { foo: 10, bar: 'hello! ...

Using the keyof operator to determine the data type of a property within a TypeScript class

According to TypeScript's documentation on the keyof operator, you can access a property of an object instance using this function below. function getProperty<T, K extends keyof T>(o: T, name: K) { return o[name]; } If you want to obtain th ...

Why is it that when I try to create a table using the "Create Table" statement, I keep getting an error saying "Near '(': syntax error"?

Error : There seems to be a syntax error near "(". Here is the SQL statement causing the issue: CREATE TABLE IF NOT EXISTS tickets ( numero INTEGER PRIMARY KEY AUTOINCREMENT, identifier VARCHAR(4) NOT NULL, subject VARCHAR(150) NOT NULL, ...

Unassigned variable in need of initialization within Angular 2

There seems to be an issue with the two-way data binding not functioning correctly. I am trying to retrieve the data using {user | json}, but I encounter an error when using [(ngModel)] = "user.username". Data Model export interface UserModel { ...

Leverage HighCharts on numerous occasions

Hello there, I'm curious about utilizing the Highcharts library in my Angular application. I have 3 tabs (sale / rental / rental & sale), each with 3 identical diagrams that display different data from my API. Currently, my setup only works on t ...