MST

星途 面试题库

面试题:Angular双向数据绑定在表单中的应用

在Angular中,如何在一个包含输入框和显示区域的表单组件里,使用双向数据绑定实现输入框内容实时显示在显示区域,同时显示区域的变化也能同步回输入框?请简要说明实现步骤并给出关键代码示例。
21.0万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 实现步骤
    • 在组件的模板文件(.html)中,为输入框使用[(ngModel)]指令绑定到组件类中的一个属性。[(ngModel)]是Angular双向数据绑定的语法糖,它结合了[ngModel](从模型到视图)和(ngModelChange)(从视图到模型)。
    • 同样在模板文件中,在显示区域(例如一个div或者span)使用插值表达式{{}}显示该属性的值。当输入框的值改变时,通过双向数据绑定,组件类中的属性值会更新,同时显示区域因为绑定了该属性也会更新;反之,若在显示区域通过某些逻辑改变了该属性的值,输入框也会同步更新。
  2. 关键代码示例
    • 组件类(.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 - fieldmatInput,如果不使用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 { }