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
  • 176
  • 1
  • 10
  • Please do not do this to use the HTML template to write in the TS file. Write it in .html – TheCoderGuy Oct 25 '19 at 15:27
  • @ZhuniqiA i did this just for the sake of this question so it's easier to see whole code. otherwise i always use a separate .html file – barley Oct 25 '19 at 15:34
  • @ZhuniqiA There's nothing wrong with doing that - if you're template is small then why not? – Katana24 Oct 25 '19 at 15:45

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
  • 2,133
  • 1
  • 15
  • 36
  • 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