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

Angular表单问题:字段非空仍弹出模态框及必填项设置咨询

Angular表单校验与模态框触发问题解决方案

问题说明

你当前创建了三个表单字段:Article、Quantity、Limit,原需求为所有字段为空时弹出错误模态框,目前存在两个待解决问题:

  • 所有字段填写完成后,点击OK按钮仍会弹出模态框
  • 希望调整校验逻辑,仅将Quantity设为必填项,只要该字段已填写,其余两个字段为空也不弹出模态框

原因分析

当前代码没有配置表单校验逻辑,点击OK按钮后会直接调用模态框打开方法,所以无论字段是否填写都会触发弹窗。

解决方案

1. 修改component.html代码

给三个输入框添加双向绑定,同时修改按钮点击事件,先触发校验逻辑,校验不通过再打开模态框:

<br><br>

<label for="article">Article</label>
<div class="input-group">
  <input type="text" class="form-control" id="article" name="article" [(ngModel)]="articleValue">
</div>

<label for="quantity">Quantity</label>
<div class="input-group">
  <input type="number" class="form-control" id="quantity" name="quantity" [(ngModel)]="quantityValue">
</div>

<label for="orderLimit">Limit</label>
<div class="input-group">
  <input type="number" class="form-control" id="orderLimit" name="orderLimit" [(ngModel)]="orderLimitValue">
</div>

<br>

<div class="row">
  <div class="col-12">
    <button class="btn btn-lg btn-outline-primary" (click)="checkForm()"> ok  </button>
  </div>
</div>

<!-- Modal -->
<ng-template #mymodal let-modal>
  <div class="modal-header">
    <h4 class="modal-title" id="modal-basic-title">Error message</h4>
    <button type="button" class="close" aria-label="Close button" aria-describedby="modal-title" (click)="modal.dismiss('Cross click')">
    <span aria-hidden="true">&times;</span>
  </button>
  </div>

  <div class="table-responsive">
    <table class="table table-striped">
      <thead>

      </thead>
      <tbody>
        <td>Fields cannot be empty</td>
      </tbody>
    </table>
  </div>


  <div class="modal-footer">
    <button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">Ok</button>
  </div>
</ng-template>

2. 修改component.ts代码

新增字段绑定变量,添加校验逻辑方法,根据需求选择对应的校验规则即可:

import { Component, ViewChild, TemplateRef } from '@angular/core';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'appBootstrap';
  closeResult: string | undefined;
  // 表单字段绑定变量
  articleValue: string = '';
  quantityValue: number | null = null;
  orderLimitValue: number | null = null;
  // 获取模态框模板引用
  @ViewChild('mymodal') mymodal!: TemplateRef<any>;

  constructor(private modalService: NgbModal) {}

  // 新增表单校验方法
  checkForm() {
    // --------------- 需求1:所有字段必填,所有字段都填写才不弹框 ---------------
    // if (!this.articleValue.trim() || !this.quantityValue || !this.orderLimitValue) {
    //   this.openModal();
    //   return;
    // }

    // --------------- 需求2:仅Quantity字段必填 ---------------
    if (!this.quantityValue) {
      this.openModal();
      return;
    }

    // 校验通过后写后续业务逻辑
    console.log('表单校验通过,可执行后续操作');
  }

  // 提取模态框打开逻辑
  openModal() {
    this.modalService
      .open(this.mymodal, { ariaLabelledBy: 'modal-basic-title' })
      .result.then(
        result => {
          this.closeResult = `Closed with: ${result}`;
        },
        reason => {
          this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        }
      );
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return `with: ${reason}`;
    }
  }
}

3. 补充FormsModule导入

如果项目还未导入双向绑定所需的FormsModule,需要在app.module.ts中添加配置:

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

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

@NgModule({
  imports: [BrowserModule, FormsModule, NgbModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 15:06:02