简体   繁体   中英

angular 2 template reference variable

i have a little issue with understanding template variable reference, when used with NgForm, here is what in the angular2 doc :

<form (ngSubmit)="onSubmit(theForm)" #theForm="ngForm">
  <button type="submit" [disabled]="!theForm.form.valid">Submit</button>
</form>

What is the value of theForm?

It would be the HTMLFormElement if Angular hadn't taken it over. It's actually ngForm, a reference to the Angular built-in NgForm directive that wraps the native HTMLFormElement and endows it with additional superpowers such as the ability to track the validity of user input.

i understand what theForm value, but i don't get from where we get the ngForm variable, is it a property of the NgForm directive?

exportAs - name under which the component instance is exported in a template

The ngForm is the Angular form directive.

You can expose your directive to the view as local variables with the exportAs key.

From the source code:

@Directive({
  selector: 'form:not([ngNoForm]):not([formGroup]),ngForm,[ngForm]',
  exportAs: 'ngForm'
  ...
})

Now you can access the ngForm directive API in your template as ngForm.

When you write this:

#theForm="ngForm"

What it does is create a local variable to your template and assign it's value to the form directive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM