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

Encountering an error from the Angular CLI compiler can be frustrating, but fear not! By making a simple change (that can always

When I was compiling my app for the first time using ng serve I encountered this error: img error However, when I made a change to one of the comp files (it could be any file), and webpack recompiled it with Angular CLI - everything worked fine. I sus ...

The communication between the child and parent components is failing to function correctly

I'm trying to send data from a child component to a parent component, but the function isn't being invoked correctly. It doesn't seem to work as expected. <router-outlet (activeElement)='getActive($event)'></router-outlet ...

Having difficulties incorporating a separate library into an Angular project

My typescript library contains the following code, inspired by this singleton example code export class CodeLib { private static _instance: CodeLib; constructor() { } static get instance(): CodeLib { if(!this._instance){ ...

Store a new JSON item in the localStorage

Currently, I am tackling a task in Angular where the objective is to store items to be purchased in localStorage before adding them to the cart. There are four distinct objects that users can add, and an item can be added multiple times. The rule is to ch ...

How can I pass Checkbox values to a function in the component in Angular 2?

Hello, I am new to Angular and currently working with NgFor. I have a requirement where I need to display elements that can be selected by the user. Upon selection, I should be able to retrieve the ID in the Component function. However, when I tried usin ...

Looking for a youtube.d.ts file to integrate the youtube-iframe-api with Angular 2?

My current challenge involves implementing the youtube iframe api for seamless video snippet display and control within an Angular 2 application. Maintaining TypeScript's type concept is crucial for both the webpack compiler and myself :). A brief ov ...

Implementation of a nested interface using a generic and union types

I am seeking to create a custom type that will enable me to specify a property for a react component: type CustomType<T> = { base: T; tablet?: T; desktop?: T; }; export type ResponsiveCustomValue<T> = CustomType<T> | T; This ...

Bringing together the functionality of tap to dismiss keyboard, keyboard avoiding view, and a submit button

On my screen, there's a big image along with a text input and a button at the bottom. The screen has three main requirements: When the user taps on the input, both the input and button should be visible above the keyboard The user must be able to ta ...

Utilize global variables in ng-apimock mocks without the need for double quotes

We integrated ng-apimock into our Angular project and successfully created mock definitions and wrote tests using protractor. Now we are looking to implement global variables in our mock definitions. Here is an example of a mock definition: { "expressi ...

The functionality of Angular JSON browserTarget has been deprecated and is no longer supported

I encountered a warning where 'borwserTarget' was deprecated in my Angular JSON file. Instead of using 'browserTarget', it prompted me to use 'builtarget'. However, it states that the data path must have a required property &a ...

Is it possible that overwriting my observable variable will terminate existing subscribers?

I am looking for a way to cache an http call and also trigger the cache refresh. My UserService is structured like this: @Injectable() export class UserService { private currentUser$: Observable<User>; constructor(private http: HttpClient) { } ...

What is the best way to integrate environment-specific configuration options into an AngularJS and Typescript project?

Currently, I am working on a project using AngularJS, Typescript, and VisualStudio. One of the key requirements for this project is to have a configuration file containing constants that control various settings such as REST API URLs and environment names. ...

Is there a way to eliminate the number spinner in Angular specifically for certain input fields?

I am facing an issue where I need to remove the numeric spinner from only a few selected inputs. By adding the following code snippet to my styles.scss file, I was able to successfully remove the spinner: /* Chrome, Safari, Edge, Opera */ input[matinput]: ...

Using Angular 2 to Pass Parameters to a Custom Validator

Within my form builder, I have declared a validator like this: import { CustomValidators } from '../../custom-form-validators'; export class SelectTicketsComponent implements OnInit { maxNumber: number = 20; ...

Exploring abstract classes for diverse implementation strategies?

Consider the following scenario: export abstract class Button { constructor(public config: IButton) {} abstract click(); } Now, we have a concrete class: class ButtonShowMap extends Button { private isShow = false; constructor(public config: IBu ...

New feature in Chrome allows credit card suggestions to be displayed in the name input field

On one specific page of my angular app, I have an input field for a name that is showing credit card suggestions. When I disable the autofill for credit cards in Chrome settings, it then shows suggestions for names instead. However, on another page with ...

Svelte: highlighting input text when selected

Is there a way to select the text of an input element when it is focused using bind:this={ref} and then ref.select()? It seems to only work when I remove the bind:value from the input element. Why is that the case, and how can I solve this issue? Thank yo ...

The latest version of IntelliJ Idea Ultimate, 2023.2.5, does not offer compatibility with the updated control flow features in Angular

I recently made the switch to Angular 17 in my project and noticed that Idea is not recognizing the new syntax in HTML templates. <mat-menu #menu="matMenu"> @for (menuItem of getData().menu.items; track menuItem) { & ...

How should I proceed if a TypeScript definition file that I am relying on is lacking a specific definition?

I have encountered an issue while using the React type definitions for my project. The focus method is missing on elements in the array returned by the refs property, which prevents me from getting a specific example to work. The compiler error states: pro ...

Tips for simulating a Ref

I have a Vue3 component where, within the setup(), I have defined the following function: const writeNote(note: Ref<Note>) => { console.log(`note ${note.id}`) } This function takes a Ref<Note>, with Note being an Interface. There are two s ...