[英]Disable validation on selection of radio button in angular
我有一個包含 3 個字段的表單:類型(單選按鈕)、名稱和地點。 如果我 select 值 'Y' 來自單選按鈕驗證應該出現名稱和地點。 如果單選按鈕驗證中的 select 值“N”不應該顯示為位置。 請幫我實現功能。 工作堆棧閃電戰: https://stackblitz.com/edit/angular-ivy-jzjh4j?file=src%2Fapp%2Fapp.component.ts
<input type="radio" formControlName="type" name="type" value="Y"/>
Yes
<input type="radio" (change)="onChange($event)"
formControlName="type" name="type" value="N"/>
No
<small class="errormessage" *ngIf="submitted && addForm.controls.type.hasError('required')">
type is required
</small>
TS
onChange(evt)
{
var target = evt.target;
if (target.checked)
{
alert('hi');
this.addForm.controls.place.valid === true;
}
else
{
this.addForm.controls.place.valid === false;
}
}
實際上,您不應該將 reactiveForm 與模板 forms 混合使用。 因此,如果您使用 fromGroup,請不要在 HTML 輸入上使用(change)
。 您必須訂閱 typescript 中的更改。 Also, your place
input is required only if Y
type is selected. 因此,如果用戶選擇N
,您必須刪除required
的驗證器,這樣您的表單才會有效。
這是您更新的堆棧閃電戰:
constructor(private formBuilder: FormBuilder) {}
addForm: FormGroup;
submitted = false;
mySubscription: Subscription;
ngOnInit(): void {
this.addForm = this.formBuilder.group({
type: ["", [Validators.required]],
name: ["", [Validators.required]],
place: ["", [Validators.required]]
});
this.mySubscription = this.addForm
.get('type')
.valueChanges
.subscribe(newValue => {
if (newValue === 'N') {
// place is not required anymore
this.addForm.get('place').setValidators([]);
} else {
// place is required
this.addForm.get('place').setValidators([Validators.required]);
}
// force valitators to be triggered, to update form validity.
this.addForm.get('place').updateValueAndValidity();
});
}
onSubmit() {
this.submitted = true;
if (this.addForm.invalid) {
return;
}
}
ngOnDestroy() {
if (this.mySubscription) {
this.mySubscription.unsubscribe();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.