Perform a child component function in Angular

I'm working on a project with a child component as a map and a parent component as a form. The parent component has a field for writing the address, and when an address is entered, an HTTP request is triggered to find the latitude and longitude coordinates. These coordinates are then displayed as markers on the map in the child component. However, currently, this functionality only works the first time the map is rendered. How can I ensure that the markers are updated every time a new address is entered?

Below is the HTML code for the parent component:

 <form [formGroup]="form">
     .....
     <input formControlName="address" (focusout)="focusoutHandler($event)" required>
     .....
     <div class="row mt-2 mb-2" *ngIf="data != undefined">
        <div class="col-12">
          <h3>MAP</h3>
          <app-map [form]="form" [data]="data"></app-map>
        </div>
      </div>
    .....
 </form>

And here is the TypeScript file:

focusoutHandler(event){
      const address = {
        address: ${this.form.get('address').value} 
      }
       this.dataService.getData(address).subscribe(
        (resp) => this.data = resp,
        error => console.log(error)
      );
    }
  }

Lastly, here is the TypeScript file for the child component:

export class MapComponent implements OnInit, OnDestroy {
  @Input() form: FormGroup;
  @Input() data;
  constructor() {
  }
  ngOnInit(): void {
    // This function should be executed every time the data changes
    this.createMap(this.data);
   }  

   createMap(data){
   ...
   } 
}

Answer №1

I created a ViewChild for my component so that I could trigger the function when typing in the input field. Here is how I set up my code:

HTML file

<form [formGroup]="form">
     .....
     <input formControlName="address" (focusout)="focusoutHandler($event)" required>
     .....
     <div class="row mt-2 mb-2">
        <div class="col-12">
          <h3>MAP</h3>
          <app-map [form]="form" [data]="data"></app-map>
        </div>
      </div>
    .....
 </form>

TS File

@ViewChild(MapComponent) mapComponent: MapComponent;
 focusoutHandler(event){
     const address = {
        address: ${this.form.get('address').value} 
      }
      this.mapComponent.getData(address);
    }
  }

TS file in child component

export class MapComponent implements OnInit, OnDestroy {
  @Input() form: FormGroup;
  @Input() data;
  constructor(private dataService: DataService) {
  }
  ngOnInit(): void {
  }

   getData(address){
     this.dataService.getData(address).subscribe(
       (resp) => this.createMap(resp),
       error => console.log(error)
      );
   }
   createMap(data){
   ...
   } 
}

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

Determine the type of sibling parameter

Creating a Graph component with configurations for the x and y axes. The goal is to utilize GraphProps in the following manner: type Stock = { timestamp: string; value: number; company: 'REDHAT' | 'APPLE' | ... ; } const props: ...

Error: Idle provider not found in the promise

Currently, I am integrating ng2-idle into an AngularJS 2 application. After successfully including the ng2-idle package in the node_modules directory of my project, I attempted to import it into one of my components as shown below: Dashboard.component.ts: ...

Is it possible for Angular to handle multiple routes for one path?

To create a landing page for anonymous users and an inbox for authenticated users without relying on manual navigation or path changes, I attempted to set up multiple components associated with the root path. However, my routing block did not work as plann ...

Exploring Next.js 13: Enhancing Security with HTTP Cookie Authentication

I'm currently working on a web app using Next.js version 13.4.7. I am setting up authentication with JWT tokens from the backend (Laravel) and attempting to store them in http-only cookies. Within a file named cookie.ts, which contains helper functio ...

Develop an outline using D3.js for the clipath shape

After successfully creating a shape with a color gradient, I encountered the need for further customization. If you are interested in this topic, check out these related questions: Add multi color gradient for different points in d3.js d3.js scatter plot c ...

What is the process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have: const data = [ { "order_id":"ORDCUTHIUJ", "branch_code":"MVPA", "total_amt":199500, "product_details":[ { ...

There seems to be an issue with transitioning the React.js page

I'm currently working on managing the page with react-hook, react-router-dom, and redux. The login functionality has been implemented, and I've written the code to redirect to the main page upon successful login. To achieve this, I utilized hi ...

Can TypeScript be used to generate a union type that includes all the literal values from an input string array?

Is it feasible to create a function in TypeScript that takes an array of strings and returns a string union? Consider the following example function: function myfn(strs: string[]) { return strs[0]; } If I use this function like: myfn(['a', &a ...

Tips for implementing a generic constant value in a TypeScript function

Is it permissible in TypeScript to have the following code snippet? function getFoo<P = "a"|"b">():string { // P represents a type, not an actual value! return "foo"; } getFoo<"a>">(); // no ...

Utilizing Enum Lowercase as Index Key Type in TypeScript

Is there a way in TypeScript to use the lower case of an enum as an index key type? I have an enum defined as: export enum NameSet { Taxi = 'Taxi', Bus = 'Bus', Empty = '', } I want to define an object with keys based o ...

What is the best way to trim a string property of an object within an array?

I am seeking a solution to access the "description" property of objects within an array and utilize a string cutting method, such as slice, in order to return an array of modified objects. I have attempted using for loops but have been unsuccessful. Here ...

Condense styles and templates into inline format using Angular-cli

Can anyone help me with configuring angular-cli to support inlining of css and html resources during the build process? I am currently using angular-cli version 1.0.0-beta.24. I attempted building with both ng buld and ng build --env=prod --target=product ...

The module "install-npm-version" could not be located

I am currently working on a project using TypeScript, which you can find at this GitHub repository. However, when I attempt to use the package in another project, I encounter an error that says Cannot find module 'install-npm-version'. Steps to ...

Angular and RxJs come together to create a compelling feature: a dynamic observable that resolves based on user

We are currently developing a messenger module that requires RxJs for emitting a value based on user interaction with another component. After attempting to use of() and passing an existing BehaviorSubject, neither method worked as expected. The desired f ...

Angular can display text on hover based on the state shown in a <td> element

Working on an Angular 7 project, I have a <td> element where I display different colors to indicate the status of a task: Red - Indicates 'Delayed' Orange - Indicates 'In progress' Grey - Indicates 'Rejected' Cu ...

What is the best way to show TypeScript code using "<code>" tags within an Angular application?

I am looking to showcase some TypeScript (angular code) as plain text on my website using prismjs. However, the Angular framework is executing the code instead. How can I prevent it from running? I have attempted enclosing it within pre and code tags wit ...

What could be the reason for receiving an undefined value when trying to determine the size of the Set

Within one of my functions, I am encountering the following code: this.personService.getPersonInfo(this.personId).subscribe((res => { let response = res.body; let num = response.personList.size; ... })) Here is what the expe ...

What is the process for creating a new type from a nested part of an existing type?

Currently, my website is being developed with a focus on utilizing code generation to ensure type safety when handling GraphQl queries. Certain components within the application receive a portion of an object as a prop. The specific type structure is outli ...

How can we recreate this ngModel text input form in a radio format for a spring boot mvc and angular application?

As I was following a tutorial on creating an employee CRUD model using spring boot and mysql server for the backend and angular for the frontend, I encountered a form group during the creation process. The tutorial originally had a text input field for gen ...

Discovering the world of Promises in TypeScript and understanding how to return specific types

Transitioning from coding in Clojure for the past two years to TypeScript has been an interesting journey. However, I've hit a bit of a roadblock today. The issue lies with my interface: interface ICustomer { id: number, first_name: string } I ...