AngularJS中的模板参考变量
angular中的模板参考变量是用来访问DOM中任何元素的所有属性。它也可以是对Angular组件或指令或Web组件的引用。模板参考变量可以指代以下内容。
- DOM element
- Directives
- Angular Component
- Web Component
步骤:
- 创建一个要用的Angular应用程序。
- 创建输入元素,并使用#标签为这个输入字段添加模板参考。
- 将此模板引用绑定在按钮点击方法 “changeTitle() “中。
- 现在在changeTitle方法中,我们可以完全访问这个输入字段,在这里我们设置了输入字段的值和焦点属性。
语法:在变量名称前使用#标签。 例如 – #geek。
<input #geek placeholder="" />
实例1:本实例通过点击按钮时关注输入文本框,说明了**模板参考变量的使用。
app.component.html:
<div style="text-align: center">
<h1 style="color: green;">GeeksforGeeks</h1>
<h3>AngularJS Template Reference Variable</h3>
<input #geek placeholder="" />
<!-- geek refers to the input element;
pass it to an event handler -->
<button (click)="changeTitle(geek)">
Click Me
</button>
</div>
在上面的HTML模板中,我们用模板参考变量 “email “创建了一个输入元素,我们还创建了一个按钮。在点击按钮时,我们访问完整的输入元素和它的所有属性。
"#geek" is template reference variable on input field
app.component.ts:
import { Component } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
changeTitle(inputElement) {
inputElement.value = "GeeksforGeeks";
inputElement.focus();
}
}
输入元素的模板参考变量可以在changeTitle()函数中访问,在点击按钮时,我们将更新输入元素的值,并使这个字段成为焦点。
app.module.ts:
import { NgModule } from "@angular/core";
import { BrowserModule }
from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule { }
输出:
例子2:在模板驱动的表单中,我们实际上是使用模板参考变量来访问表单数据。
app.component.html:
<div style="text-align: center">
<h1 style="color:green">GeeksforGeeks</h1>
<h3>AngularJS Template Reference Variable</h3>
<h4>{{ email_address }}</h4>
<form #itemForm="ngForm" (ngSubmit)="onSubmit(itemForm)">
<input ngModel #email="ngModel"
type="email" placeholder="Email" name="email" />
<button type="submit">Submit</button>
</form>
</div>
因此,在这里我们使用模板参考变量访问表单元素上的表单数据,在表单提交时,我们显示通过表单字段提供的输入电子邮件。
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
email_address = 'geek@geek.com';
onSubmit(form) {
this.email_address = form.value.email;
}
}
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule }
from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent,
bootstrap: [AppComponent],
})
export class AppModule { }
因此,完整的表单字段是使用 “itemForm “模板参考变量访问的,我们在浏览器中显示电子邮件地址。
输出: