Tips for transmitting information from a parent function to its child counterpart

Hello, I am looking to transfer data from a parent component to a child component in Angular 6. Here is my code for the child.ts file:

this.rest.sendRequest('GET', 'station', null).subscribe(
        value => {
            this.data = value['Station'];
            this.source.load(this.data);
            console.log(this.data);
        },
    );

And here is my code for the parent.ts file:

addStation() {
  this.rest.sendRequest( 'POST', 'station', this.station).subscribe();
}

For the child.html file:

<nb-card>
  <nb-card-header>
    List of Stations
  </nb-card-header>

  <nb-card-body>
    <ng2-smart-table [getValueFromParent]="value" [settings]="settings" [source]="source" (deleteConfirm)="onDeleteConfirm($event)" (editConfirm)="onEditConfirm($event)">
    </ng2-smart-table>
  </nb-card-body>
</nb-card>

And for the parent.html file:

    <nb-card>
      <nb-card-header>
         Station
      </nb-card-header>
      <nb-card-body>
        <div class="row">
          <div class="col-md-4">
            <nb-card>
              <nb-card-header>
                <p>Add New Station</p>
              </nb-card-header>
              <br>
              <nb-card-body>
                <h3>Add Station</h3>
                <form (ngSubmit)="addStation()" #form="ngForm" autocomplete="on" >
                <div class="form-control">
                    <div>
                    <label for="title">
                      Title
                    </label>
                    <input class="form-control" id="title" name="title" nbInput [(ngModel)]="station.title" placeholder="Title">
                  </div>
                  <div>
                    <button nbButton type="submit" >Add Station</button>
                  </div>

                </div>
                </div>
                </form>

              </nb-card-body>
            </nb-card>
          </div>

          <div class="col-md-8">
            <ngx-smart-table></ngx-smart-table>
          </div>
        </div>

I would like the table to update automatically when the form is submitted. How can I achieve that?

Note: My "this.station" is an object and "this.data" is an array. Additionally, I am using ng2-smart-table.

Answer №1

Inside the file parent.ts

const value: string;

addStation() {
  this.value = this.station;      // Assign the value of this.station to value.
  this.rest.sendRequest( 'POST', 'station', this.station).subscribe();
}

Next, in the parent.html file where you include your child component.

<ngx-smart-table [getValueFromParent]="value"></ngx-smart-table>

In the child .ts file

export class ChildComponent implements OnInit {
  @Input() getValueFromParent: string;   // GetValueFromParent now holds the value of this.station.
  constructor() {}

  ngOnInit() {}
}

Answer №2

If you are utilizing ngx-smart-table, make sure to check out the following link for guidance on how to pass source data into the table:

import { Ng2SmartTableModule, LocalDataSource } from 'ng2-smart-table';
//include local data source

source: LocalDataSource; //add a property to your component

constructor() {

this.source = new LocalDataSource(this.data);
}//initialize the source

//Connect with ngx-smart-table

<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>

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

Enforce TypeScript's compliance with class types

Here is a code snippet that I came across: class A { public var1: string = 'var1'; } class B { public var1: string = 'var1'; public var2: string = 'var2'; } const instance: A = new B(); console.log(instance insta ...

Challenges with promises in Angular Firebase Realtime DB

Having some difficulties with Angular and Firebase Realtime DB. In my database service, I created a function like this: getAllProject() { return firebase.database().ref('project').once('value').then((snapshot) => { if (snapsh ...

Confirm that the attributes of a JSON object align with an Enum

Having a Lambda function that receives a JSON object from the Frontend over HTTPS, I need to perform validation on this object The expected structure of the body should be as follows (Notifications): interface Notifications { type: NotificationType; f ...

Expected single URL matching error in HttpTestingController

While testing my http service class and attempting to test the request, I encountered the following error: Expected one matching request for criteria "Match URL: https://beneficios/api/v1/processobeneficio/1111111111111/timeline", found none. I'm puz ...

Why is the Routes module failing to acknowledge the component?

I am in the process of developing my own Portfolio and decided to use Angular 12. Despite following all of the instructions on angular.io, I am facing challenges with Routing. To demonstrate my work more effectively, I have created a Stack Blitz: My Portf ...

When configuring Gatsby with Typescript, you may encounter the error message: "You cannot utilize JSX unless the '--jsx' flag is provided."

I am currently working on a Gatsby project and decided to implement Typescript into it. However, I encountered an error in my TSX files which reads: Cannot use JSX unless the '--jsx' flag is provided. What have I tried? I consulted the docume ...

Plunker encounters failure with Angular 6 reactive form demonstration

I am working with an example in Angular 6 that looks like this: //our root app component import { Component, NgModule, VERSION, Injectable } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { For ...

Clicking on the sub kendo panelbar item activates the parent kendo panelbar item

Utilizing a Kendo Angular UI panelbar within the sidepanel as a treemenu with submenu's, each item is linked to the Angular router routes array via routerLink. An issue arises when opening the submenu, where the parent menuitem's path is followe ...

What could be causing the lack of updates in my shared service across all components?

I have implemented an Angular2 app where I am initializing an authentication service called LocalStorage which I want to be accessible across all my components: bootstrap(AppComponent, [ ROUTER_PROVIDERS, LocalStorage ]); The definition of the Lo ...

What causes images to unexpectedly expand to fill the entire screen upon switching routes in Next.js?

I'm in the process of creating a website using Next and Typescript, with some interesting packages incorporated: Framer-motion for smooth page transitions Gsap for easy animations One issue I encountered was when setting images like this: <Link&g ...

Enhance your list items created with ngFor by incorporating a variety of icons using Ionic

Is there a way to assign custom icons to individual items in a list created with ngFor? Would it be more effective not to automatically generate the menu items? app.html <ion-menu [content]="mainContent"> <ion-content id="side-menu" style="backg ...

Getting the search bar's result set and simultaneously wiping out the existing data

If we input the value 5, a result set is displayed if there is a match. However, entering 56 results in an error message stating "no data found". The issue arises when clearing the first value 6, causing the function to no longer search for the input 5. ...

What steps are involved in developing an Angular library wrapper for a pre-existing Javascript library?

Imagine having a vanilla Javascript library that is commonly used on websites without any frameworks. How can you create an Angular library that can be easily installed via npm to seamlessly integrate the library into an Angular application? The process o ...

Generic partial application fails type checking when passing a varargs function argument

Here is a combinator I've developed that converts a function with multiple arguments into one that can be partially applied: type Tuple = any[]; const partial = <A extends Tuple, B extends Tuple, C> (f: (...args: (A & B)[]) => C, ...a ...

Issue: The spy MovieService.getWatchListedMovies was expected to have been called during the angular Unit Testing, but it was

There is a component file named watchlist which relies on MovieService(service) to retrieve movies. Invoking ngOnInit() will trigger MovieService.getWatchlistedMovies() The component code is provided below, export class WatchlistComponent implements ...

An issue has occurred: Cannot access the properties of an undefined object (specifically 'controls')

I encountered an error message stating "TypeError: Cannot read property 'controls' of undefined" in the code that I am not familiar with. My goal is to identify the source of this error. Below is the HTML code snippet from my webpage: <div ...

Building a dynamic form in Angular that includes dynamic event binding and dynamic function execution

Hey there, I'm just starting out with angular and I'm looking to create a form that can render using JSON data which also includes events and functions. Here's the setup: <div *ngFor="let form of forms; index as i "> <div ...

Determine in React whether a JSX Element is a descendant of a specific class

I am currently working with TypeScript and need to determine if a JSX.Element instance is a subclass of another React component. For instance, if I have a Vehicle component and a Car component that extends it, then when given a JSX.Element generated from ...

Fairly intricate React function component declaration with TypeScript

const withAuth = () => <OriginalProps extends {}>( Component: React.ComponentType<OriginalProps & IAuthContextInterface> ) => { } (withAuth()(PrivateRoute)) // this is how the HOC called Could someone simplify what this function d ...

Setting up GoogleProvider with Next Auth in your Next 13 application: A step-by-step guide

Having some trouble setting up the authentication system for my NextJS 13 Experimental App and src folder. Every time I try to authenticate, I get redirected to http://localhost:3000/api/auth/error with a 404 error. I have configured Google OAuth Credenti ...