1

Here is a weird problem in Angular:

<input #pin1 type="password">
<p>You entered: {{pin1.value}}</p>

If you type something in <input>, the <p>'s content will not change which means pin1.value does not have value, does it mean the variable reference #pin1 does not work?

On the other hand, if we add a function to pass the reference, it will work.

<input #pin2 type="password" (input)="test(pin2)">
<p>You entered: {{pin2.value}}</p>

where test=function(x){console.log(x);}

For this <input>, if we type something, the the <p>'s content will change to corresponding text which implies #pin2 works.

So I do not understand why we must do it? why we must use function to pass variable reference firstly then we can use it? Why can't we just declare a variable reference, and then directly use it in template expression or interpolation?

closed as off-topic by gnat, BobDalgleish, Thomas Owens Apr 18 at 16:23

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for assistance in explaining, writing or debugging code are off-topic here. These can be asked on Stack Overflow if they include the desired behavior, a specific problem or error, and the shortest code necessary to reproduce it in the question (see Minimal, Complete, and Verifiable Example)." – gnat, BobDalgleish, Thomas Owens
If this question can be reworded to fit the rules in the help center, please edit the question.

  • Consider use [(ngModel)]="something" on the input, and {{ something }} on the paragraph. – Cristhian Gz Dec 19 '17 at 13:23
0

Use ngmodel to bind to values in the template:

<input id="name" name="name" class="form-control"
  required minlength="4" appForbiddenName="bob"
  [(ngModel)]="hero.name" #name="ngModel" >

or as a component:

import {NgForm} from '@angular/forms';

@Component({
  selector: 'example-app',
  template: `
    <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
      <input name="first" ngModel required #first="ngModel">
      <input name="last" ngModel>
      <button>Submit</button>
    </form>

    <p>First name value: {{ first.value }}</p>
    <p>First name valid: {{ first.valid }}</p>
    <p>Form value: {{ f.value | json }}</p>
    <p>Form valid: {{ f.valid }}</p>
  `,
})
export class SimpleFormComp {
  onSubmit(f: NgForm) {
    console.log(f.value);  // { first: '', last: '' }
    console.log(f.valid);  // false
  }
}

References

Not the answer you're looking for? Browse other questions tagged or ask your own question.