You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何将输入框文本保存到组件变量中?

嘿,我来帮你搞定这个Angular的小问题!你的代码里有几个基础的语法和概念问题,我一步步给你梳理修正:

1. 修正模板里的双向绑定指令

你现在用的ng-model是AngularJS(老版本)的语法,Angular 2+需要用双向数据绑定的[(ngModel)]语法,这样模板里的输入框才能和组件类的数据同步。修改后的home.component.html代码如下:

Username: <input [(ngModel)]="username"><br>
Password: <input [(ngModel)]="pass"> 
<button (click)="login()">Login</button>
2. 调整组件类的属性与方法逻辑

首先得在HomeComponent类里声明username和pass这两个属性,作为模板绑定的数据源;然后在login()方法里,要用this来访问组件类的属性({{}}是模板插值语法,不能在TS文件里使用);另外,前端打印内容应该用console.log()而不是print()。修改后的home.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  // 声明用于绑定的属性,初始化空字符串
  username: string = '';
  pass: string = '';

  constructor() { }

  ngOnInit(): void {
  }

  login() {
    const usr = this.username;
    const password = this.pass;
    // 用模板字符串拼接更简洁
    console.log(`User is ${usr}, Password is ${password}`);
  }
}
3. 关键:导入FormsModule

使用[(ngModel)]必须依赖Angular的FormsModule,所以你需要在对应的模块(通常是AppModule)里导入并注册它,否则会报错:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // 导入FormsModule

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule // 添加到imports数组中
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

做完这些调整后,当你在输入框输入内容,点击Login按钮时,login()方法就能正确获取到你输入的用户名和密码啦!

内容的提问来源于stack exchange,提问作者Chris Dunn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:25:36