【发布时间】:2025-11-30 20:50:02
【问题描述】:
我正在尝试创建一个简单的多步骤表单(步骤 1、2 3)。我正在使用 *ngIf 来隐藏和显示步骤。 这是我尝试过的。
这是我的组件.html
<div *ngIf="step1" class="step1">
<h1>STEP 1<h1>
</div>
<div *ngIf="step2" class="step2">
<h1>STEP 2<h1>
</div>
<div *ngIf="step3" class="step3">
<h1>STEP 3<h1>
</div>
<div class="button-container">
<button class="float-left" (click)="stepBackward()" >Back</button>
<button class="float-right" (click)="stepForward()">Next</button>
</div>
这是我的组件.ts
import { Component, Inject, OnInit, Renderer2 } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
@Component({
selector: 'app-step-builder',
templateUrl: './step-builder.component.html',
styleUrls: ['./step-builder.component.scss']
})
export class StepBuilderComponent implements OnInit {
constructor(private pageTitle: Title,
private router: Router,
private fb: FormBuilder,
private http: HttpClient,
@Inject(ENV_TOKEN) private ENV: any,
private renderer: Renderer2,
private snackBarService: SnackbarService){}
stepCounter = 0;
step1 = true; step2 = false; step3 = false;
stepArray = new Array();
stepForward() {
this.stepArray[this.stepCounter] = false;
console.log(this.stepCounter);
this.stepCounter++;
this.stepArray[this.stepCounter] = true;
console.log(this.stepCounter);
}
stepBackward() {
console.log(this.stepCounter);
this.stepArray[this.stepCounter] = false;
this.stepCounter--;
console.log(this.stepCounter);
}
}
所以基本上我想要做的是,我有一个stepCounter,它在开始时为 0,当我点击 Forward 时,计数器会增加,同时还试图通过设置隐藏当前容器(步骤 1)将 this.step1 设置为 false,我使用数组存储 step1、step2 和 step3 并使用 stepCounter 作为索引,我尝试将当前步骤的值设置为 false。然而这并没有隐藏 div,step1 的值为 false,但 div 没有隐藏。这整个方法听起来可能很愚蠢。有没有更好更简单的方法实现功能?
【问题讨论】:
标签: angular