Angular Element ref input get value doesn't work directly in the template

Viewed 552

I don't understand why this doesn't show the value

<p>
    <input #my type="text" id="name" name="name">
</p>
value {{my.value}}

while this do show the value

<p>
    <input #my type="text" id="name" name="name"  (input)="my" >
</p>
value {{my.value}}
2 Answers

In the first code sample you are adding a reference to the HTML input but you are not watching events coming from it, therefore Angular change detection doesn't get triggered for your component.

In the second one you are watching the input events, therefore change detection gets triggered.

You can check this for the first sample, by adding private changeDetector: ChangeDetectorRef to your constructor and adding a code piece in your onInit function to check for changes every second: setInterval(() => this.changeDetector.detectChanges(), 1000);

However this is just for debugging purposes, what you really should do is, adding a method which will set the input value to a local variable like this:

HTML:

<p>
    <input type="text" id="name" name="name" (input)="setInput($event.target.value)" >
</p>
    value {{inputValue}}

TS:

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  public inputValue: string;

  constructor() {}

  ngOnInit() {}

  public setInput(value: string): void {
    this.inputValue = value;
  }
}

Because in the second case you register the input event. So when you write something in the second input the event updates its value. In the first case when you write something the input event doesn't do anything.

Related