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?

1
  • Consider use [(ngModel)]="something" on the input, and {{ something }} on the paragraph. Commented Dec 19, 2017 at 13:23

1 Answer 1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.