Update of input not available

Does anyone know how to effectively transfer data from one page to another programmatically? I'm facing an issue where updating an input field doesn't work unless I manually edit it afterwards. Is there a better way to achieve this?

Another problem I'm encountering is that it takes two clicks for a button to update the input field. I suspect this delay is related to waiting for a response from the Arcgis API, but I'm not sure how to address this issue.

HTML

<form id="container_categorySelect" [formGroup]="details" (ngSubmit)="onSubmit()">
    <img src="Location_Icon.svg" id="locationIcon" (click)="getLocation()">
    <input class="form-control form-control-lg" id="addressSelect" type="text" placeholder="Address" formControlName="location" [(value)]="currentPosition">
    <button mdbBtn type="submit" id="submitBtn" mdbWavesEffect> Locate </button>
</form>

Typescript

  details:FormGroup = new FormGroup({
    category: new FormControl(''),
    location: new FormControl('')
    }
  );
  currentPosition: string;
  curLocation: any;

constructor(private router: Router,
    private addressService:AddressServicesService, 
    ) {}

// Retrieve location based on current location
  getLocation(){
    // Checks if GPS is supported
    if(navigator.geolocation){
      navigator.geolocation.getCurrentPosition(response => {

        // Retrieves address based on coordinates
        this.curLocation = this.addressService.retrieveLocation(response);
        this.currentPosition = this.curLocation.address.ShortLabel
      });
    } else {
      alert("Geolocation is not supported by this device")
    }
  }

addressService Service

  // Retrieve Location Variables
  currentLocation: any;
  reverseGeo: string = "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?f=pjson&featureTypes=&location=";

  // Retrieves location based on coordinates
  retrieveLocation(position:any){
    this.http.get(this.reverseGeo + position.coords.longitude+"%2C"+position.coords.latitude).subscribe(response =>{
      // Converts response(Object) to type "any"
      this.currentLocation = response;
    });
    return this.currentLocation;
  }

Answer №1

The issue here is that you are binding to both the value property and providing a formControlName. It's like saying y = x; and then y = p; and expecting y to be both x and p at the same time. Only one of them will be applied, which is not the behavior you want in your application.

With that being said, your updated HTML should look like this:

<form id="container_categorySelect" [formGroup]="details" (ngSubmit)="onSubmit()">
    <img src="Location_Icon.svg" id="locationIcon" (click)="getLocation()">
    <input class="form-control form-control-lg" id="addressSelect" type="text" placeholder="Address" formControlName="location" >
    <button mdbBtn type="submit" id="submitBtn" mdbWavesEffect> Locate </button>
</form>

To simplify the code, we can inject the FormBuilder class into our constructor and use it to create the form:

constructor(..., private fb: FormBuilder) {}
  details = this.fb.group({
    category: [],
    location: []
  });

Then, to update the value, you can simply use the setValue() function on the FormControl:

Change the line

this.currentPosition = this.curLocation.address.ShortLabel;
to:

const currentPosition = this.curLocation.address.ShortLabel;
this.details.get('location').setValue(currentPosition)

Finally, your code should now look like this:

  getLocation() {
    // Check if GPS is supported
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(response => {
        // Get address based on coordinates
        console.log("getting");
        this.curLocation = this.addressService.retrieveLocation(response);
        const currentPosition = this.curLocation.address.ShortLabel;
        this.details.get('location').setValue(currentPosition)
      });
    } else {
      alert("Geolocation is not supported by this device");
    }
  }

Answer №2

One way to check if an input is available is by utilizing the ngOnChanges() method. If necessary, you can temporarily halt the rendering of HTML until the required @Input() becomes available using *ngIf.

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

Issue with displaying PHP variable in JavaScript alert box

In my PHP code, I have a variable called LeagueLink. The goal is to display a specific text (Already have a league...) and a link to a popup window when the user is not logged in. Everything seems to be working fine, except when I click on the link, noth ...

React.js application experiencing a lack of response from EventSource on-message function

Currently, I am in the process of migrating an established production application from jquery to react.js. The backend is built using Java (spring boot) and the existing app utilizes Server-Sent Events to push specific types of notifications from the serve ...

Do not allow the use of <p> or <br> tags in

I would like to enable basic styling with <strong>, <em> and lists using ckeditor. But I do not want any <br> or paragraph tags because I normalize my content and prefer it to be clean. After some research online, I came across this sol ...

Generating hills with PlaneGeometry in Three.js

Currently, I am searching for a straightforward technique to generate non-uniform hills in Three.js. By utilizing particles and positioning them with a sine wave algorithm like the following snippet: x = Math.random() * 1000 y = Math.sin( x / freq ) * ...

Using AngularJS with Spring MVC and @RequestParam

As a newcomer to AngularJS, I have a Spring controller that retrieves an object from the database based on its id. I want to pass this id using @RequestParam in AngularJS. However, when attempting to do so, I encountered the following error message: "Error ...

The date error from day.js in Firefox is not valid

My date is formatted as 2022-01-27 09:23:48 UTC and I am trying to parse it into MMMM-DD-YYYY format (Jan-27-2022) using day.js. The parsing works well in Chrome, but Firefox returns an 'Invalid' result. import dayjs from "dayjs" const ...

Guide on displaying a tooltip for an object in an Angular component using Bootstrap syntax

i have a data object structured like this var obj = {"test price type ty dynamic ": 10, test: 7, pricetype1u: 0, Price type 3: 0, Price type 2: 0} in my Angular component HTML, with Bootstrap styles applied, I've written the following code ...

Guide to generating an HTML select element that initiates corresponding Angular service functions when the selection is changed

I am looking to develop an Angular component that will feature a dropdown or select option for users to choose from various methods provided by different services. The selected method will be executed upon selection change, and these methods are essentiall ...

The TypeScript `unknown` type restricts the use of non-unknown types in function parameters

Why is there an error in this code? const x: unknown[] = ['x', 32, true]; // OK const y: (...args: unknown[]) => unknown = (xx: number) => {}; // ERROR // Type '(xx: number) => void' is not assignable to type '(...args: u ...

Erase Mistake in Pop-up Angular JSON Information and Bootstrap

Encountering an ERROR TypeError: Cannot read property 'id' of undefined while attempting to delete data in a modal using Bootstrap. When I click the button, I correctly receive the data in JSON format in the modal (as shown in the image). Any ide ...

choosing a date range

My goal was to determine the number of days between a "fromDate" and a "toDate," with the restriction that the user should not be able to select a date range of more than 90 days. I am utilizing the Dojo framework to create a date calendar. Below is the co ...

Using only Node.js, demonstrate the image

I want to show an image using only Node.js without involving HTML or ID's. I have been looking for solutions but most examples I find use HTML, which I prefer not to use. Unfortunately, I don't have any code to share, but I'm wondering if th ...

Capturing and Receiving Voice Audio in DiscordJSv14

Currently, I am developing a Discord bot in JS using DiscordJSv14 and I want the bot to extract audio from a voice chat and forward it to another bot, functioning like a spy or eavesdropper bot. Although I have successfully connected the bot to the voice ...

Unlock the ability to retrieve the current Ember route directly within a component

I have a unique custom Ember component embedded within a controller. Currently, I am attempting to dynamically retrieve the name of the current route. In order to access the controller, I use: this.get('parentView') However, I am facing diffi ...

Stop an item from being included based on a boolean value

I need to iterate through an array of IDs called "world". The idea is that if the ID value in world exists in myArray[n].id, then I want to remove the entire element from myArray. If it doesn't exist, then I want to add it to myArray. world = ["124241 ...

Prevent selection of future dates in Kendo UI Calendar Widget

Can someone please advise on a method to disable future dates (i.e., gray them out) in the Kendo UI Calendar widget? I've attempted hiding the future dates, but it doesn't look good. I've also tried different ways to gray them out without su ...

What is the best way to apply ngClass to an element based on certain conditions?

My service maintains the state of opened blocks like so: export class BlocksStateService { public openedBlockState = new Map<number, boolean>; setState(id: number, state: boolean) { this.openedBlockState.set(id, state); } getStat ...

How is it possible for this code to function when the object is not explicitly defined within the javascript code?

While using JSLint, I encountered an issue where it stated: 'matte_canvas' is not defined. Although I have not explicitly defined 'matte_canvas' in my javascript code, it does output the canvas element in the console. Below is the code ...

Changing pricing on pricing table with a click

Looking to implement a price changing button that functions similar to the one found at this LINK: If anyone knows of any JavaScript or other solution, please provide me with some guidance. Thank you in advance. ...

Encountering a module injection error in AngularJS related to the ui.grid feature during my first experience with it

Trying to develop an AngularJS app, encountering the following error upon running the code: Uncaught Error: [$injector:modulerr] Failed to create module myApp: Error: [$injector:modulerr] Failed to create module ui.grid: Error: [$injector:nomod] Module &a ...