2

My question is about an example explained in the Angular Documentation about Angular template input variable.

https://angular.io/guide/template-syntax#expression-context

Template reference variable example from Docs.

I tried to run this sample code and I am expecting the text entered in the input text box been displayed next to it. However, it doesn't work that way. I don't have this variable as viewChild inside the component as it is not mentioned in the Angular doc Page. Could you suggest here what is my mistake or my understanding is incorrect?

My sample code:

app.component.ts

import { Component } from '@angular/core';

import { Hero } from './hero';

@Component({
  selector: 'app-root',
  template: `

  <h1>{{title}}</h1>

  <label>Type something:
  <input #customerInput>{{customerInput.value}}
</label>
`,
styleUrls:["app.component.css"]
})

export class AppComponent {
  testInput = "Hello"
  title = 'Tour of Heroes';
  recommended = true;

}

Output:

Output screenshot

As I am a beginner with Angular, this may be a very basic mistake. However, I would use your feedback to learn and understand better. thank you.

2 Answers 2

4

In that case it's better to use backing field value in component to which you can bind the value of the input via two way binding [(ngMode)]="value", afterwards you can use that field to display the value using already familiar binding like {{value}}. But if you want to run this example, you need to add some dom event listener, so angular will run change detection when it fires, it could be keyup for example:

<input #customerInput (keyup)="true">{{customerInput.value}}

Change detection it's a separate topic. I don't know why on angular page they put such example. Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

2

If you check the example given with the documentation you can find (keyup)="0" in parent div element (check below image). Unfortunately this is not mentioned in the document.

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.