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

Angular项目按钮失效、输入值不更新问题求助

Angular应用问题:按钮点击事件失效与双向绑定不更新

我正在开发一个基于TypeScript和HTML的Angular小应用,遇到两个问题:

  • 按钮点击事件saveNumbers()、getValue()无法正常触发
  • 输入框通过[(ngModel)]绑定的数值始终无法更新

注:ngOnInit里调用saveNumbers()只是为了观察程序运行流程,实际需要通过按钮触发。


组件模板

<body>

  <h1>{{ title }}</h1>

  <div id="grid">
    <table>
      <tr *ngFor="let row of tableData">
        <td *ngFor="let cell of row">
          {{ cell }}
        </td>
      </tr>
    </table>
  </div>

  <div id="stevila">
    <p>Števila od 7 do 45</p>
    <input type="number" [(ngModel)]="vrednost" min="7" max="45" name="stevilo1" required>
    <input type="number" [(ngModel)]="vrednost2" name="stevilo2" min="7" max="45" required>
    <input type="number" [(ngModel)]="vrednost3" name="stevilo3" min="7" max="45" required>
    <input type="number" [(ngModel)]="vrednost4" name="stevilo4" min="7" max="45" required>
    <input type="number" [(ngModel)]="vrednost5" name="stevilo5" min="7" max="45" required>
    <input type="number" [(ngModel)]="vrednost6" name="stevilo6" min="7" max="45" required>
    <input type="number" [(ngModel)]="vrednost7" name="stevilo7" min="7" max="45" required>
    <button (click)="saveNumbers()">Kombiniraj</button>

    <input #inputElement type="text" />
    <button (click)="getValue()">Get Value</button>

  </div>

  <div id="grid2">
    <table class="zbiralnik" *ngIf="stevila.length">
      <tr *ngFor="let row of stevila" class="zbiralnik">
        <td *ngFor="let cell of row" class="zbiralnik">
          {{ cell }}
        </td>
      </tr>
    </table>
  </div>

  <router-outlet></router-outlet>
</body>

组件代码

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { clearInterval } from 'node:timers';

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

export class AppComponent implements OnInit {
  @ViewChild('inputElement') inputElement!: ElementRef;

  title = 'Loto srečka';

  tableData: number[][] = []; //ime tabele in kaj shranjuje

  //generiranje cifer

  vrednost: any = 10;
  vrednost2: any = 7;
  vrednost3: any = 14;
  vrednost4: any = 17;
  vrednost5: any = 19;
  vrednost6: any = 23;
  vrednost7: any = 26;

  stevila: string[][] = [];

  ngOnInit(): void {
    this.tableData = this.tabela(); //shrani rezultat tabele
    this.stevila = this.saveNumbers(); //izvede celotno funkcijo
  }

  saveNumbers() {
    console.log('Button clicked!');
    const tabelica: number[] = [this.vrednost,
    this.vrednost2,
    this.vrednost3,
    this.vrednost4,
    this.vrednost5,
    this.vrednost6,
    this.vrednost7].filter(val => val !== null) as number[];

    for (let i = 0; i < 7; i++) {
      this.stevila[i] = Array(7).fill('');

      for (let j = 0; j < this.stevila[i].length; j++) {
        this.stevila[i][j] = tabelica[i] + " " + tabelica[j];

        if (i == j || i == j + 1 || i == j + 2 || i == j + 3 || i == j + 4 || i == j + 5 || i == j + 6)
          this.stevila[i][j] = "";


      }//druga

    }//prva

    return this.stevila;
  }

  tabela(): number[][] {
    const arr: number[][] = Array.from({ length: 5 }, () => Array(5));
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr[i].length; j++) {
        let stevilo = Math.floor(Math.random() * (45 - 7 + 1)) + 7;

        while (arr[i].includes(stevilo)) { // pregleduje ali je v tej vrsti tabele že to število, če je true, potem naredi novo, ce ke false gre dalje
          stevilo = Math.floor(Math.random() * (45 - 7 + 1)) + 7;
        }

        arr[i][j] = stevilo;
        console.log(arr[i][j]);
      }

    }
    return arr;
  }

  getValue() {
    console.log(this.inputElement.nativeElement.value); // This will print the input value
  }
}

问题排查与解决方案

1. 核心原因

Angular的[(ngModel)]双向绑定及表单相关事件依赖**FormsModule**支持,未导入该模块时,绑定和事件都会失效。

修复步骤

打开根模块文件(通常是app.module.ts),添加FormsModule导入:

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    FormsModule, // 新增此行
    // 保留原有RouterModule等导入
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2. 额外优化建议

  • 移除ngOnInit中this.stevila = this.saveNumbers()的赋值,避免初始化时覆盖按钮触发的结果
  • 将绑定变量类型从any改为number,提升类型安全性:
    vrednost: number = 10;
    vrednost2: number = 7;
    // 其余变量同理
    
  • 简化saveNumbers中的条件判断,用if (i >= j)替代多个i == j + n的冗余判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 23:00:03