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

Angular // binding innerHTML data

I'm having trouble setting up a dynamic table where one of the cells needs to contain a progress bar. I attempted using innerHTML for this, but it's not working as expected. Any suggestions on how to approach this? Here is a snippet from my dash ...

Retrieve the dimensions of an image once rendering is complete, using Angular

I'm currently working on obtaining the rendered size of an image within a component. By utilizing the (load) event, I can capture the size of the image as it appears at that particular moment (pic1), as well as its "final" size after the page has fini ...

Storing Angular header values in local storage

saveStudentDetails(values) { const studentData = {}; studentData['id'] = values.id; studentData['password'] = values.password; this.crudService.loginstudent(studentData).subscribe(result => { // Here should be the val ...

What is preventing the mat-slide-toggle from being moved inside the form tags?

I've got a functioning slide toggle that works perfectly, except when I try to move it next to the form, it stops working. When placed within the form tag, the toggle fails to change on click and remains in a false state. I've checked out other ...

Issue with Angular's ngOnChanges Lifecycle Hook Preventing Function ExecutionWhen attempting to run a function within Angular's ngOn

In the midst of my evaluation process to ensure that specific values are properly transmitted from one component to another using Angular's custom Output() and EventEmitter(), I am encountering some issues. These values are being sent from the view of ...

Encountering a hiccup with dependencies during the transition to Angular 9 with jodit-angular

Encountering the following error when attempting to execute the command npm install after migrating Angular to version 9. Error npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-pro ...

What is the best way to utilize project references with multiple tsconfig files?

Let's say I have three separate projects to work on: shared frontend backend In order to use the shared project as a reference in both the frontend and the backend, I need to make a few adjustments. The backend utilizes commonjs modules while the fr ...

What is the best approach to implement server-side rendering in Next.js while utilizing Apollo React hooks for fetching data from the backend?

I have a Next.js project that is utilizing Apollo GraphQL to retrieve data from the backend. My goal is to render the page using server-side rendering. However, I am encountering an obstacle as the React hooks provided by GraphQL Apollo prevent me from cal ...

An email value being recognized as NULL

create-employee.html <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <span><input type="text" [required]="!standingQueue" class="form-control" name="exampleInputEmail1" ...

The specified "ID" type variable "$userId" is being utilized in a positional context that is anticipating a "non-null ID" type

When attempting to execute a GraphQL request using the npm package graphql-request, I am exploring the use of template literals. async getCandidate(userId: number) { const query = gql` query($userId: ID){ candidate( ...

Angular2: The NgFor directive is designed to work with Iterables like Arrays for data binding

I'm currently working on a university project to develop a web application consisting of a Web API and a Frontend that interacts with the API. The specific focus of this project is a recipe website. Although I have limited experience with technologies ...

The value of this.$refs.<refField> in Vue.js with TypeScript is not defined

During the process of converting my VueJs project to TypeScript, I encountered an error related to TypeScript. This issue arises from a component with a custom v-model implementation. In the HTML, there is an input field with a 'plate' ref that ...

Restrict the frequency of requests per minute using Supertest

We are utilizing supertest with Typescript to conduct API testing. For certain endpoints such as user registration and password modification, an email address is required for confirmation (containing user confirm token or reset password token). To facilit ...

How can I access DOM elements in Angular using a function similar to the `link` function?

One way to utilize the link attribute on Angular 2 directives is by setting callbacks that can transform the DOM. A practical example of this is crafting directives for D3.js graphs, showcased in this pen: The link attribute: When it comes to manipula ...

Duplicate Component Names Detected in Angular 2

Just starting out with Angular 2 and I'm working on an app. I've organized my components into folders based on their functionality, here's how it looks: - app --components ---users ----create ----edit ---collaborations ----create ----edit ...

The element 'router-outlet' in Angular 9.0 is not recognized within a lazily loaded module

My attempt at adding a new lazyloaded module to the app component is running into an issue. When I try to include child routes for the new module, an error stating that 'router-outlet' is not a known element:in lazy loaded module is thrown. In t ...

It appears that the blob data is not being received in the message sent from the websocket server to my Angular 2 Observable

Having trouble converting some html/javascript to Angular 2 and encountering an issue with blob data not being received in messages from the websocket host to the Angular 2 Observable. Text messages are being sent successfully from the websocket host, but ...

Creating a higher order component (HOC) that utilizes both withRouter and connect functions in React

I am currently working with the following stack: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87f5e2e6e4f3c7b6b1a9b6b4a9b6">[email protected]</a> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Inquiry regarding the implementation of DTO within a service layer parameter

I have a query regarding the choice of service layer to use. // 1 export class SomeService{ async create(dto:CreateSomeDto) {} } or // 2 export class SomeService{ async create(title: string, content: string) {} } It appears that most individuals opt ...

Tips on mocking an ngrx selector within a component

Within a component, we utilize an ngrx selector to access various segments of the state. public isListLoading$ = this.store.select(fromStore.getLoading); public users$ = this.store.select(fromStore.getUsers); The fromStore.method is formed using the ngrx ...