Yesterday, we talked about Template Reference Variables. Today, I want to show you how a directive can be accessed with a Template Reference Variable.
You’ve probably seen that syntax before:
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" >
Code language: HTML, XML (xml)
That syntax is possible because the NgForm
directive is exported using the following syntax (actual Angular source code here):
@Directive({
exportAs: 'ngForm'
})
Code language: TypeScript (typescript)
The above code enables the usage of Template Reference Variables such as #myForm="ngForm"
. This technique is widely used in Angular forms and component libraries to expose public directive properties (and methods) to your component’s template.
For instance, we can access myForm.value
or myForm.valid
in an expression.
ngModel
is exported that way, too.