0

component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template:
      `<input #data (input)="f()" />
      {{ data.value }}`
})
export class AppComponent {

  f() {}
}

i am able to get data.value using the above code snippet, but when i remove (input)="f()" part from input element, data.value is no longer getting updated when i type in input element

barley
  • 166
  • 1
  • 9

1 Answers1

2

You should update the data by using Angular Two-Way data binding

For you example this would be:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template:
      `<input [(ngModel)]="input" />
      {{ input }}`
})
export class AppComponent {

  public input: string = '';
}

Stackblitz: https://stackblitz.com/edit/angular-gchfdb

This has to be done because Angular Change Detection is based on events, XHR and Timers. If no listeners are attached to the input no events will be fired, thus the template will not be evaluated.

Modifying the value through Input() or any other Action would trigger the ChangeDetection.

(Bad Practice: You can also run Change Detection manually via ChangeDetectorRef.detectChanges().)

Daniel Habenicht
  • 1,817
  • 12
  • 32
  • i know two way binding would solve this, but i am still curious about why local reference works the way i mentioned in the question – barley Oct 25 '19 at 15:39