Angular 5 - Customizing input view with unique values

I am using ngx-bootstrap to implement a typeahead feature on an input field.

<input type="text" class="form-control with-icon" placeholder="Address ..."
      formControlName="address" [typeahead]="addressDataSource"  typeaheadOptionField="fullAddress" />

Here is how my addressDataSource is structured :

[
  {
    id: '1',
    fullAddress: '44000 - Nantes'
  },
  {
    id: '2',
    fullAddress: '77400 - Paris'
  }
 ....
]

The issue I am facing is that when I select a value, the input field shows the fullAddress correctly. However, I want the actual value of the input field to be only the postal code (e.g. 44000 or 77400).

I attempted to create a Directive as follows :

constructor(private model: NgControl) { }

  @HostListener('input') inputChange() {
    const newValue = this.model.value.split(' ')[0];
    this.model.control.setValue(newValue);
    this.model.valueAccessor.writeValue(this.model.value);
  }

While the value does change, the displayed value in the input field also changes.

Answer №1

After some trial and error, I was able to successfully implement the solution. For anyone who may benefit from it, here is the directive code that did the trick:

constructor(private model: NgControl) { }

  @HostListener('input') inputChange() {
    const newValue = this.model.value.split(' ')[0];

    this.model.control.setValue(newValue, {
        emitEvent: false,
        emitModelToViewChange: false
      });
  } 

Although I got it working now, I still don't understand why it didn't work with the previous code. If anyone knows the reason behind it, please feel free to share and I'll update my answer accordingly.

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

The MUI NativeSelect component is causing a disruption to the submission process in a

I am looking to automatically submit my form whenever there is a change (for example, when the selected value in a dropdown menu changes). However, I have been facing some challenges when using NativeSelect from MUI. This is the code I have: const onSubm ...

What is the best way to access dynamic URL parameters in the Next.js 13 app router from a nested server-side component?

This query pertains to the Server-Side components in Next.js 13 app router: I have a good grasp on how the slug parameter is passed to the default function in app/blog/[slug]/page.tsx: export default function Page({ params }: { params: { slug: string } }) ...

Exploring Angular2 components featuring setInterval or setTimeout functions

I have a basic ng2 component that interacts with a service to retrieve carousel items and automatically cycle through them using setInterval. Everything functions properly, but I encounter the error "Cannot use setInterval from within an async test zone" w ...

Navigating the Command Prompt following the compilation of ng serve

Upon setting up a new Angular 5 project, installing the necessary tools including Angular CLI and Node.js, I successfully ran ng serve via command prompt. However, when attempting to install Bootstrap through the command prompt, it seemed unresponsive. Wha ...

Error in Webpack: "Module cannot be found: unable to resolve in tsx files"

Attempting to deploy my React projects to the development server has been successful on my local Macbook. However, issues arose when deploying the React project to PM2 in the development server. Here are some excerpts from the error messages: 2021-01-20 1 ...

Tips for sending input from the command line to an Angular application

I am working on a node.js angular application. After building it, I run it with node on a specific server. How can I pass a value to my Angular app? Ultimately, I want to display text on my user interface depending on the command line argument's value ...

(adjust) upon selecting a different radiobutton

I have a dilemma with two radio buttons. I am trying to trigger an event when button B is either checked or unchecked. Unfortunately, I am unable to attach any event to button A. <input type="radio" id="A" name="radiogrp" v ...

TestingCompilerFactory is not available as a provider

Currently troubleshooting my test file to identify the issue that is hindering a successful test run: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Component, Directive, Input, OnInit } from '@angula ...

I am experiencing a 404 error when attempting to import a local JS file in Angular

After creating a new project with "ng new xxx", all you need to do is add one line of code in index.html: <!doctype html> <html lang="en> <head> <meta charset="utf-8> <title>Bbb</title> <base href="/&g ...

Retrieve the unchanged data from the source before any modifications using ag-Grid

Is the original data saved anywhere when accessing data with the ag-Grid API? For instance, can it be retrieved from: api.getRowNode(id) This information could come in handy, especially if you want to highlight an edited cell by comparing values and chan ...

Variability in determining union types for matched conditional results

In my experience, I have noticed a discrepancy in TypeScript's type inference when dealing with conditional return statements in functions. I have two identical functions, register and register2, outlined below: const register = (step: 1 | 2) => { ...

What is the correct way to apply type in the .call() method?

I need help finding a solution for the following issue interface IName { name:string; } let obj1:IName = { name: "LINUS" } function profileInfo (age:number,location:string):string{ return `${this.name} is ${age} years old and is from ${location ...

How to Activate Animation Post-Page Load in Angular 8, Overcoming ExpressionChangedAfterItHasBeenCheckedError

Trying to solve a crucial question concerning animating an element after the page has fully loaded. Despite extensive research, I have yet to find a simple and efficient solution. Can anyone offer some advice? Once the mobile page is loaded, I want the log ...

update icon when a router link becomes active

<div class="menuItem mb-3" *ngFor="let menuItem of menuItems"> <a routerLink="{{menuItem.link}}" routerLinkActive="active"> <img src="{{menuItem.icon}}" alt="{{menuItem.name}}" /> <p class="text-center f-12">{{me ...

Best way to observe something

For the project I am currently working on, I have an observable that returns values and I need to update my local variable based on the value returned by this observable. I have identified two possible ways to achieve this: directly subscribing to the obs ...

How can one efficiently deactivate all fields in an Angular form for a short period?

There are two ways I know to achieve this (demonstration of both available here). Both methods can be used for template-driven and reactive forms as they rely on the FormGroup API. formGroup.enable() and formGroup.disable() <form ngForm> <inpu ...

Prevent ESLint from linting files with non-standard extensions

My .estintrc.yaml: parser: "@typescript-eslint/parser" parserOptions: sourceType: module project: tsconfig.json tsconfigRootDir: ./ env: es6: true browser: true node: true mocha: true plugins: - "@typescript-eslint" D ...

Guide on incorporating TypeScript ambient declaration interfaces within an interface specified in a d.ts file

I am looking to create a helper in a .ts file like the following: class ResponseHelper implements IResponseHelper {...} The IResponseHelper is a simple .d.ts file with the structure: import * as mongoose from 'mongoose'; import * as express fr ...

Tips for validating an object with unspecified properties in RunTypes (lowercase object type in TypeScript)

Can someone please confirm if the following code is correct for validating an object: export const ExternalLinks = Record({}) I'm specifically asking in relation to the repository. ...

Within Angular2 NGmodule, I aim to dynamically load two distinct sets of route modules depending on certain conditions

In Angular2, I am looking to load two different sets of route modules - one for jobseekers and the other for employers. Both sets will have the same URLs but will contain different modules for jobseekers and employers. Therefore, I need a way to dynamicall ...