Angular 2 components not properly handling two-way binding errors

Exploring how to achieve two-way binding in Angular 2, I am currently working with the following parent component setup:

app.component.html:

<child [(text)]="childText" (textChanged)="textChanged($event)"></child>
<span>{{childText}}</span>

app.components.ts:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  childText = 'Initial text value';

  textChanged(newValue: string) {
    console.log(this.childText); // This always logs "Initial text value"
    console.log(newValue); // Outputs the new value from the child component input
  }
}

child.component.html:

<input #inputEl [value]="text" (keyup)="text = inputEl.value">

child.component.ts:

@Component({
  selector: 'child',
  templateUrl: 'child.component.html',
  styleUrls: ['child.component.scss']
})
export class ChildComponent {
  private _text: string;
  @Output() textChanged: EventEmitter<string> = new EventEmitter<string>();

  @Input()
  get text(): string {
    return this._text;
  }

  set text(value) {
    this._text = value;
    this.textChanged.emit(value);
  }

  constructor() { }
}

Upon changing the text within the input element of the child component, the {{childText}} displayed in the app component template reflects the new value, while this.childText retains its initial value.

I wondered if there was a way to update this.childText without relying on a callback from the child component. Additionally, why does

<span>{{childText}}</span>
only reflect the updated value?

Answer №1

When implementing two-way binding with [(x)], you need a property named x and an event called xChange. In the code snippet provided, there was a small error in the spelling of textChanged.

export class ChildComponent {
  @Input() text: string;
  @Output() textChange: EventEmitter<string> = new EventEmitter<string>();

  onKeyUp(val) {
    this.text = val;
    this.textChange.emit(this.text);
  }
  ...
}

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

Using style binding and ngStyle doesn't appear to be effective for setting a background image within a DIV element in Angular5

After facing difficulties in customizing the spacing of Angular material cards, I decided to create my own cards. However, during this process, I encountered an issue where I needed to set an image as a background inside a div. Despite trying various CSS ...

Seeking a guide on how to effectively utilize Angular 6 for consuming REST API and performing CRUD operations

I am a beginner with Angular and I am currently using Version 6, specifically the CLI tool. My main focus right now is learning how to make REST API calls. I have searched for tutorials on this topic but unfortunately, none of them have been successful fo ...

I am eager to learn how to integrate the "fs" module from Node.js into an Electron project powered by Angular

As I venture into writing my first desktop app using Electron and Angular5, I have encountered a roadblock while working with the fs module. Despite importing fs correctly (without errors in Visual Studio Code and with code completion), I faced an issue wh ...

Having trouble with Angular's ng-tags-input? Are you getting the error message "angular is not defined"? Let

I recently created a new Angular project using the following command: ng new "app-name" Now, I'm attempting to incorporate ngTagsInput for a tag input feature. However, every time I try to build and run my app, I encounter an error in my browser con ...

Transfer a file to Laravel using $request->input()

Is there a way to upload my file to FTP when I'm sending the data from Angular using JSON format instead of using $request->file("Fichier1") in Laravel? Here is an example of how the data is sent from Angular to Laravel: https://i.stack. ...

Confirming that the NGRX Dictionary value is set

After upgrading from Angular 7.1.4 to 8.2.0 and Typescript from 3.1.6 to 3.5.3, I encountered an issue with identification of array items. Prior to the upgrade, TypeScript correctly recognized that the array item was not undefined. However, post-upgrade, ...

"Exploring Angular's versatile table component for dynamically displaying object values in a loop

I am facing an issue with my generic table component in the software I am currently developing. The problem arises when trying to loop through and display all the values in the table. My employeeList contains data fetched from the backend successfully, bu ...

What is the method to save data into the browser's local storage when the reload button is clicked in AngularJS?

Is there a way to store data into the localstorage in AngularJS when the reload button is clicked? I've tried using the code below, but it doesn't seem to work: window.onbeforeunload = function (event) { var $body = angular.element(documen ...

When using TypeScript and Material UI, it is important to assign a value to boolean attributes

Trying to implement Material UI code with Typescript for a DisplayCard component, but encountering an error message: (34,23): Value must be set for boolean attributes. The challenge lies in identifying which attribute value is missing... Here is the samp ...

Steps to refresh a variable when the SMS read plugin successfully completes

I'm attempting to make a post call within the success callback of my SMS read plugin code. I can successfully print _this.otpnumber in the console. Please refer to my stack trace image link getSMS(){ var _this= this; var fil ...

Navigate to the login page in Angular 2

Initially, the template login (login.component) needs to be called first. Once the login is complete, then app.component will be loaded. Is it possible to achieve this? And if so, how can I do it? Edited Question: I am already using CanActivate. Apologi ...

Issue with ion-datetime component causing unexpected value changes when both maximum and minimum values are set

My current project includes the use of ion-datetime. Here are some details regarding the Ionic version being used: Ionic: Ionic CLI : 5.4.16 Ionic Framework : ionic-angular 3.9.5 @ionic/app-scripts : 3.2.2 Below is a snippet showcasi ...

Navigating Angular's Credit Card Input Functionality

I am looking to limit the input capacity to 16 numbers and add a space between each set of 4 numbers. After conducting an extensive search for a credit card input that allows users to enter 16 digits with a " - " or space in between, all results were for ...

AngularFire2 - Deleting an item with Observable - Issue with last item not being removed from the User Interface

When I execute this function, the item is deleted from my Firebase database. However, in my Angular 2 app, when it reaches the last entry, it removes it from the database but does not remove it from the list displayed in my *ngFor loop. Strangely, upon ref ...

The instanceof operator does not recognize the value as an instance and is returning false, even though it

Is there a method to verify the current instance being used? This is what I am logging to the console: import { OrthographicCamera } from 'three'; // Later in the file: console.log(camera instanceof OrthographicCamera, camera); and the result ...

Dynamically render a nested component, created within the parent component, using a directive

Can a nested component be dynamically rendered as a directive within the parent component? Instead of using the standard approach like this: <svg> <svg:g skick-back-drop-item /> </svg> where "skick-back-drop-item" is the s ...

Create a unique NPM package tailored to my needs, available for easy installation across all of my projects

My plan is to create a custom "skin" on top of bootstrap for various UI projects. Instead of manually copying and pasting styles and components from my current Angular 5 project, I want to develop an NPM package that can be easily installed in new projects ...

Problems encountered while trying to install the angular2-meteor package using npm

Attempting to kick off a fresh angular2-meteor project with the command: npm install angular2-meteor --save Encountering a slew of red errors (shown below) and I'm puzzled by their significance. Already executed npm install npm -g and npm ...

Developing a custom package containing personally crafted type definitions and importing them into the project

I'm in need of creating a private npm package specifically for custom type definitions (typedefs) that are hand-written d.ts files not generated by TypeScript. Since these are proprietary, they cannot be added to DefinitelyTyped. The folder structure ...

How to integrate Three.js into Angular 14 while managing dependencies

I'm currently working on developing a web app using angular cli and incorporating three.js for enhanced product interaction. Despite watching numerous tutorials, I've been unable to successfully integrate three js into angular 14. It seems to wor ...