我正在使用ngIf指令根据选择动态添加/删除DOM中的字段
但如果我选择AKG然后切换到其他选项,表单状态将变为无效
这是我的代码 -
<div class="form-group">
<label for="college">College:</label>
<label class="validations" @load *ngIf="!regForm.controls.members.controls[i].controls.college_name.valid && regForm.controls.members.controls[i].controls.college_name.touched">Please Select a College!</label>
<select class="form-control" id="college" required placeholder="Select College" formControlName="college_name" (change)="makevalid(i)">
<option value="akg">Ajay Kumar Garg Engineering College</option>
<option value="other">Others- Please Specify Below</option>
</select>
</div>
<div class="form-group" *ngIf="regForm.controls.members.controls[i].controls.college_name.value === 'other'">
<label for="cname">Enter College Name:</label>
<label class="validations" @load *ngIf="!regForm.controls.members.controls[i].controls.college_name.valid && regForm.controls.members.controls[i].controls.college_name.touched">Please Enter a College Name!</label>
<input type="text" class="form-control" id="cname" required placeholder="Enter Your College Name" formControlName="college_name_entry">
</div>
<div class="form-group" *ngIf="regForm.controls.members.controls[i].controls.college_name.value === 'akg'">
<label for="studno">Student Number:</label>
<label class="validations" @load style="font-size: 0.8em;" *ngIf="!regForm.controls.members.controls[i].controls.student_no.valid && regForm.controls.members.controls[i].controls.student_no.touched">Please Enter a Valid Student No.!</label>
<input type="text" class="form-control" id="studno" pattern="^([1][4-7]\d{5}[Dd]{0,1})$" required placeholder="Enter Your Student Number" formControlName="student_no">
</div>
和打字稿 -
makevalid(index) {
console.log(index);
if (this.regForm.value.members[index].college_name == 'other') {
(<FormControl>(<FormGroup>(<FormArray>this.regForm.controls.members).controls[index]).controls.student_no).updateValueAndValidity();
}
else {
(<FormControl>(<FormGroup>(<FormArray>this.regForm.controls.members).controls[index]).controls.college_name_entry).updateValueAndValidity();
}
}