Angular 2+不使用多布尔变量实现输入框显隐的替代方案
优化方案
你可以通过单步骤变量+统一跳转函数的方案替代多个Boolean变量和独立切换函数,代码更简洁,后续拓展步骤也更方便。
效果演示



优化后TypeScript代码
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-takwa', templateUrl: './takwa.component.html', styleUrls: ['./takwa.component.css'] }) export class TakwaComponent implements OnInit { // 用单变量替换三个Boolean变量,记录当前展示的步骤 currentStep = 1; // 接入响应式表单可直接实现输入框非空校验逻辑 inputForm: FormGroup; constructor(private fb: FormBuilder) { this.inputForm = this.fb.group({ test1: ['', Validators.required], test2: [''], test3: [''] }) } ngOnInit() {} // 统一跳转函数,无需为每个步骤单独写切换方法 goToStep(step: number) { // 跳转第二步时自动校验第一个输入框是否非空 if (step === 2 && this.inputForm.get('test1')?.invalid) { return; } this.currentStep = step; } }
优化后HTML代码
<form [formGroup]="inputForm"> <!-- 第一个输入框 --> <div *ngIf="currentStep === 1"> <input formControlName="test1"> <button (click)="goToStep(2)" [disabled]="inputForm.get('test1')?.invalid">suivant</button> </div> <!-- 第二个输入框 --> <div *ngIf="currentStep === 2"> <input formControlName="test2"> <button (click)="goToStep(3)">suivant</button> <button (click)="goToStep(1)">retour</button> </div> <!-- 第三个输入框 --> <div *ngIf="currentStep === 3"> <input formControlName="test3"> <button (click)="goToStep(2)">retour</button> </div> </form>
该方案的优势:
- 无需维护大量Boolean变量,后续拓展到任意数量的步骤,都不需要修改TS逻辑,仅新增对应HTML片段即可
- 不用为每个切换场景单独编写函数,统一通过传参控制跳转
- 原生支持表单校验逻辑,直接满足第一个输入框非空才能显示第二个输入框的需求
内容的提问来源于stack exchange,提问作者Boubaker Takwa
相关产品推荐
相关产品推荐

