A guide on extracting and transferring data from one field to another within Angular 2

In my form, I have two input fields. My goal is to take the text from the first field, replace the first part with different text, and dynamically populate it into the second field. While I have managed to retrieve the value from the first field easily, I am struggling to figure out how to replace and snip the text on keyup. Below is the code snippet: Component HTML

<div class="labels">Real Name</div> 
<div class="lbl">
     <input #realName type="text" [(ngModel)]="actualName" (keyup)="trigger()">
 </div>
 <div class="labels">Cyber Name</div>
 <div class="lbl">
     <input #cybName type="text"[(ngModel)]="cyberName"> 
  </div>

Component TS

@ViewChild('realName') realName: ElementRef;
@ViewChild('cybName') cybName: ElementRef;

trigger() {
  this.cybName.nativeElement.value = this.realName.nativeElement.value;
}

Currently, I am simply setting the cyber name to be the same as the real name on every keyup event. However, I actually want to snip the first 4 characters of the real name and replace them with "droid", while keeping the rest of the characters intact. For example, if the real name entered is "Alexys", the desired output should be "droidys".

I understand that handling this on keyup might not be the best approach. I would appreciate any suggestions or assistance in implementing this functionality. Thank you.

Answer №1

If you're looking for a simple fix to your problem, consider this solution:

Modifications in html:

<input #realName type="text" [ngModel]="actualName" (ngModelChange)="trigger($event)">

Modifications in typescript:

trigger(newActualName) {
  this.actualName = newActualName;
  this.cyberName = `Droid${event.substring(4)}`;
}

By updating the model (actualName and cyberName), the input will automatically reflect these changes with the updated values.

Note: It is advised by Angular to avoid using ElementRef and directly manipulating the DOM. For more information, visit here.

Answer №2

To manipulate your input, you can utilize the splice method for cutting it up. Below are some assumed use cases:

"AAAAAA" -> "droidAA"

"AAAA" -> "droid"

"AA" -> "AA"

const strLength = this.realName.nativeElement.value && this.realName.nativeElement.value.toString().length;

if (strLength >= 4) {
    this.cybName.nativeElement.value = 'droid' + this.realName.nativeElement.value.toString().splice(4, strLength);
} else {
    this.cybName.nativeElement.value = this.realName.nativeElement.value;
}

Additionally, strive to avoid using nativeElement unnecessarily. Instead, work directly with the variables themselves.

if (this.actualName && this.acutualName.length >= 4) {
    this.cyberName = 'droid' + this.actualName.splice(4, this.acutualName.length);
} else {
    this.cyberName = this.actualName;
}

Answer №3

It seems like your intention is to concatenate the substr:

let digitalAlias = 'byte';
let humanName = 'Samantha';
let digitalHumanAlias = `${digitalAlias}${humanName.substring(4)}`;
console.log(digitalHumanAlias);

Answer №4

Here are some steps to try:

<div class="header">Full Name</div> 
<div class="input-field">
     <input #fullName type="text" [(ngModel)]="completeName">
 </div>
 <div class="header">Online Alias</div>
 <div class="input-field">
     <input #alias type="text"[ngModel]="'online' + completeName.substring(6)"> 
  </div>

Answer №5

There are numerous approaches to tackle this problem, as evident from the various responses. Personally, I would opt for utilizing a pipe to accomplish this task. This concept is demonstrated in a functional example available at this link.

To create a custom pipe, follow these steps:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'robotNamePipe'})
export class RobotNamePipe implements PipeTransform {
  transform(value: number, exponent: string): string {

  // Insert your logic here

    return `${value} - Anything you desire!`;
  }
}

... and then use it in your HTML like so:

<div class="labels">Real Name</div> 
<div class="lbl">
     <input #realName type="text" [(ngModel)]="actualName">
 </div>
 <div class="labels">Cyber Name</div>

<p>Robot name: {{realName.value | robotNamePipe}}</p>

In truth, allowing users to modify the generated droid name might not be ideal - don't you agree?

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

Changing the structure of an array of objects

Currently, I am dealing with an API that provides an array of objects structured like this: [{match_id: "255232", country_id: "41", country_name: "England", league_id: "152", league_name: "National League", match_date: "2020-01-01", match_status: "", matc ...

Ensure Jest returns the accurate file paths for images in a TypeScript and React environment

I'm currently developing a React application and I have come across an issue with importing images. My usual method of importing images is as follows: import image1Src from 'assets/img1.png"; For testing purposes, I need to be able to make ...

Struggling to make type definitions work in react-hook-form 7

Upon defining the types of my form fields, I encountered an issue where each field seems to take on all three different types. This is puzzling as I have specified 3 distinct types for my 3 different fields. What could be causing this confusion? https://i ...

Tips for assigning identifiers to dynamically generated elements in KnockOutJS

Is it possible to assign unique IDs to dynamically created elements in KnockOutJS? I have two spans - one for the button and another for a small icon in the corner of the button. There are a total of 6 elements like this, but they do not have unique IDs. ...

Tips for preventing the occurrence of numerous instances of braintree.setup in Angular

I am encountering an issue with a Braintree payment form displayed in a modal window: $scope.displayModalBraintree = function () { $scope.modal = 'modal_payment_form.html', $scope.$on('$includeContentLoaded', function () { ...

Encountering an issue with importing external JavaScript files in the App.js file during React development

Currently, I am embarking on the development of a basic starter app that deals with SMTP anonymously in React. This project is primarily for educational purposes. Prior to diving into actual development work, I have decided to keep things simple and focus ...

Ensure that a required checkbox is included within a list of items generated dynamically through ngFor

I am working with an array of items in Angular, using ngFor to display a list of checkboxes. I need to implement validation that ensures at least one checkbox remains mandatory. For example, if one checkbox is checked and another is unchecked, I want to p ...

Caution: A non-boolean attribute received a value of `false`. What is the correct way to provide a boolean value?

I'm encountering an issue with the code below: react-dom.development.js:67 Warning: Received false for a non-boolean attribute high. If you want to write it to the DOM, pass a string instead: high="false" or high={value.toString()}. Despi ...

Animating background images using a single data attribute

I'm attempting to create a smooth animation between different background images stored in a single data attribute. The goal is for each image to load sequentially, with the first one appearing immediately and the rest following after a 5-second delay. ...

Next js is throwing an error because it cannot accept objects as a React child. Instead, it found an error message stating "Response not successful: Received status code 401."

This app showcases Github issues by utilizing the graphql API. After finishing the app, I encountered an error without making any changes. The technologies used for this project include Next.js, Typescript, Material UI, Tailwind CSS, and GraphQL. https: ...

Error: Attempted to access 'embed' before it was initialized (hi)

module.exports = { name: "slowmode", description: "Set the slowmode of a channel.", execute(message, args, Discord) { if(!message.member.hasPermission("ADMINISTRATOR")) { return message.reply(&q ...

Combining PouchDB with Vue.js for seamless integration

Has anyone successfully integrated PouchDB / vue-pouch-db into a Vue.js application before? I encountered an error when attempting to define the PouchDB database. Here are the definitions I tried: import PouchDB from 'pouchDB' or import PouchDB ...

Testing Angular 11 methods using Jest unit tests within a .then block

Currently, I am running jest unit tests in Angular 11 and facing an issue while testing methods within the .then method. It seems like the test methods are not being executed at the expect method. I need guidance on how to structure the test code to ens ...

Values are not being retrieved from dynamic form fields

I am currently utilizing dynamic forms within Angular to construct my form. Each ingredient is represented by a select of available options, but since multiple ingredients can be added, I need to generate selects dynamically. Here is the HTML code snippet ...

Upgrading an Angular 1 directive to Angular 4

I have created a custom directive in Angular 1 that allows drag and drop functionality for images in a web application. Here is the original code: 'use strict'; angular.module('abc').directive("imageFileRead", ['$document', ...

Is there a way to test a function call within ngOnChanges using Angular Jasmine?

In my Angular app, I have a child component that invokes a function in the ngOnChanges lifecycle hook. export class GameComponent implements OnInit, OnChanges { ngOnChanges(changes: SimpleChanges) { this.generateRandomIcon(); } generateRan ...

Tips for displaying an edit action icon when hovering over specific text

Looking for a way to display or hide the edit icon when hovering over specific text? Take a look at this snippet of HTML code: <ul> <li> <a id="pop" href="javascript:;;" data-content="test Desc" data-id="123"> &l ...

What is the process for obtaining multiple arrays from a webassembly function invocation?

I'm searching for a solution to retrieve multiple arrays of varying sizes from a webAssembly function call. Initially, I considered using a struct with multiple arrays and returning it, but I couldn't find any information on how to receive that s ...

Steps to enable the submit button in angular

Here's the code snippet: SampleComponent.html <nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)"> <label nz-radio nzValue="passed">Passed</label> <label nz-rad ...

Create an Interactive Form Generator in Angular

I'm currently working on an Angular project that involves Dynamic Inputs. When I click on a button, new inputs are created and now I want to use FormBuilder to get the data. However, I am unsure of how to go about this. Although I am familiar with us ...