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

Ionic2技术实现:页面加载隐藏提交按钮,两输入框值匹配时显示

Got it, let's work through this problem step by step. You want the submit button hidden when the page loads, and only make it visible once the second input's value matches the first one. Here's how to implement this with your existing Ionic/Angular setup:

1. Update Your HTML Template

First, let's complete the second input binding and add the submit button with visibility control. We'll use Angular's *ngIf directive to conditionally render the button:

<ion-item>
  <ion-label floating>Reading</ion-label>
  <ion-input type="number" formControlName="readFirst" [(ngModel)]="readFirst"></ion-input>
</ion-item>

<ion-item>
  <ion-label floating>Retype Reading</ion-label>
  <!-- Call our check method on value change, and bind ngModel to readSecond -->
  <ion-input (ngModelChange)="checkValues()" type="number" formControlName="readSecond" [(ngModel)]="readSecond"></ion-input>
</ion-item>

<!-- Submit button: hidden initially, shows only when values match -->
<button ion-button type="submit" *ngIf="isMatch" block>Submit</button>

2. Add Logic to Your Component Class

In your corresponding .ts file, define the necessary variables, initialize the match state to false (so the button starts hidden), and implement the checkValues method to compare the inputs:

import { Component } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'page-your-component', // Replace with your actual component selector
  templateUrl: 'your-component.html' // Replace with your template path
})
export class YourComponent {
  public readFirst: number;
  public readSecond: number;
  public isMatch = false; // Default to false to hide the button on load
  public readingForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    // Initialize your reactive form as needed
    this.readingForm = this.formBuilder.group({
      readFirst: [''],
      readSecond: ['']
    });
  }

  checkValues() {
    // Check that both values exist and are equal
    this.isMatch = 
      this.readFirst !== undefined && 
      this.readSecond !== undefined && 
      this.readFirst === this.readSecond;
  }
}

3. Quick Notes

  • We use *ngIf instead of [hidden] because *ngIf removes the button from the DOM entirely when hidden, which is cleaner than just hiding it with CSS. If you prefer to keep it in the DOM but hidden, you can swap *ngIf="isMatch" with [hidden]="!isMatch".
  • The check ensures both values are not undefined to avoid showing the button when only one input is filled.
  • Since your inputs are type="number", we're comparing numeric values directly—no need to handle string trimming or type conversion here.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:03:46