【问题标题】:Submit button not firing and validations also not firing提交按钮未触发且验证也未触发
【发布时间】:2026-01-12 01:45:01
【问题描述】:

我正在实现一个简单的 Angular-CLI 模板表单,提交按钮没有触发并且验证也不起作用,当我按下提交时,值没有像我预期的那样显示在浏览器控制台中,我提到了 html 和 typescript。

html

<nav class="navbar navbar-inverse">
    <div class="container">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Dating App</a>
      </div>
      <div id="navbar" class="navbar-collapse collapse">
        <ul class ="nav navbar-nav">
          <li><a href ="#">Matches</a></li>
          <li><a href ="#">Lists</a></li>
          <li><a href ="#">Messages</a></li>
        </ul>
        <form #loginForm ="ngForm" class="navbar-form navbar-right" (ngSubmit)="Login()">
          <div class="form-group">
            <input placeholder="Email" class="form-control" type="text" required  [(ngModel)]="model.username" name ="username">
          </div>
          <div class="form-group">
            <input placeholder="Password" class="form-control" type="password" required [(ngModel)]="model.password"  name ="password">
          </div>
          <button type="submit" [disabled]= "!loginForm.valid" class="btn btn-success">Sign in</button>
        </form>
      </div><!--/.navbar-collapse -->
    </div>
  </nav>

打字稿

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

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {

  model: any ;

  constructor() { }

  ngOnInit() {

  }

  Login() {
    console.log(this.model);
  }

}

【问题讨论】:

  • 当您尝试在 console.log 语句中打印一些随机文本时会发生什么?
  • 文本将出现在浏览器控制台中,表示提交按钮触发
  • Login(value)console.log(value) 中将 loginForm.value 作为参数传递。

标签: angular angular-cli angular2-template angular-template angular-validation


【解决方案1】:

我认为您的问题是您可能没有在 app.module.ts 中添加“FormsModule”。

在你的app.module.ts

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


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


@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent,

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

在你的app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  private model:any[]=[];

  constructor(){
  }

  private Login() {
    console.log(this.model);
  }
}

这个解决方案对我有用。希望这会有所帮助。谢谢。

【讨论】: