【发布时间】:2018-08-28 13:02:58
【问题描述】:
我有一个响应式表单,加载时不需要任何字段。如果选择了将其他表单元素添加到 formGroup 的选项,则新显示的字段将是所有必需的。 如果昵称字段被隐藏,那么您应该能够提交表单就好了。如果显示昵称,则需要昵称字段并且禁用提交按钮,直到昵称字段已满。 这是我想做的一个示例。
我的问题是,如何在表单元素显示/隐藏后启用/禁用验证?
App.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
App.component.ts
import { Component, OnInit } from '@angular/core';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'My Reactive Form';
constructor(
private fb: FormBuilder
) {}
myForm: FormGroup;
showNick: boolean = false;
ngOnInit() {
this.myForm = this.fb.group({
'firstName': new FormControl(),
'nickName': new FormControl('', Validators.required),
'lastName': new FormControl()
})
}
toggleNick() {
this.showNick = !this.showNick;
}
}
app.component.html
<form [formGroup]="myForm">
<div class="my-box">
<label>
First Name
<input type="text" formControlName="firstName">
</label>
</div>
<div class="my-box nickname">
Nickname? <a (click)="toggleNick()">yes / no</a>
</div>
<div class="my-box" *ngIf="showNick">
<label>
Nickname
<input type="text" formControlName="nickName">
<span class="validation-message" *ngIf="!myForm.controls['nickName'].valid && myForm.controls['nickName'].dirty">
This field is invalid
</span>
</label>
</div>
<div class="my-box">
<label>
Last Name
<input type="text" formControlName="lastName">
</label>
</div>
<button [disabled]="myForm.invalid">Submit</button>
</form>
【问题讨论】:
-
您似乎还没有编写代码来执行您所描述的操作。有什么阻止你?你的问题在哪里?
-
我无法完成我需要的工作。我将在顶部编辑我的问题。基本上,如果元素被隐藏,那么 formGroup 中仍然需要一些东西。隐藏表单元素后如何切换验证?
-
这是我的工作示例以及 DeborahK 提供的解决方案:stackblitz.com/edit/angular-twjirf
标签: angular forms validation reactive