面试题答案
一键面试- 实现步骤:
- 在组件的模板文件(
.html
)中,为输入框使用[(ngModel)]
指令绑定到组件类中的一个属性。[(ngModel)]
是Angular双向数据绑定的语法糖,它结合了[ngModel]
(从模型到视图)和(ngModelChange)
(从视图到模型)。 - 同样在模板文件中,在显示区域(例如一个
div
或者span
)使用插值表达式{{}}
显示该属性的值。当输入框的值改变时,通过双向数据绑定,组件类中的属性值会更新,同时显示区域因为绑定了该属性也会更新;反之,若在显示区域通过某些逻辑改变了该属性的值,输入框也会同步更新。
- 在组件的模板文件(
- 关键代码示例:
- 组件类(
.ts
文件):
- 组件类(
import { Component } from '@angular/core';
@Component({
selector: 'app - form - component',
templateUrl: './form - component.html',
styleUrls: ['./form - component.css']
})
export class FormComponent {
inputValue: string = '';
}
- 模板(
.html
文件):
<mat - form - field>
<input matInput [(ngModel)]="inputValue" placeholder="输入内容">
</mat - form - field>
<div>显示区域: {{inputValue}}</div>
上述示例中使用了Angular Material的mat - form - field
和matInput
,如果不使用Angular Material,普通的input
标签同样适用,例如:
<input type="text" [(ngModel)]="inputValue">
<div>显示区域: {{inputValue}}</div>
并且要确保在模块中导入了FormsModule
,例如在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({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }