Reputation: 145
I am developing an Angular app where i use check boxes in a formgroup. I have second form group with multuiple text inputs. I want to enable the selected text input in the second form when particular check box in other form is enabled.
FormGroup1
<div class="list">
<form [formGroup] = "f1FormGroup" (ngSubmit)="f1(f1FormGroup.value)" #form1 = "ngForm" >
<h2>i1</h2>
<h5> <input type="checkbox" name="i1" value="i1" [(ngModel)]="i1.isChecked" > i1 </h5>
<h5><input type="checkbox" name="i2" value="i2" [(ngModel)]="i2.isChecked" > i2 </h5>
</form>
</div>
FormGroup2
<div id="i1m" class="modal">
<!-- Modal content -->
<div class="col-sm-5">
<span class="close" (click) = "close1()">×</span>
<h2>RV</h2>
<form class="st" [formGroup] = "i1mFormGroup">
<h6>Material</h6>
<input type="text" id="m1" placeholder="Optional" name="m1" value="m1">
<h6>TC</h6>
<select matNativeControl required>
<option value="1">C</option>
<option value="2">H</option>
<option value="2">S</option>
</select>
<h6>SH</h6>
<input type="text" id="m2" placeholder="1" disabled>
<button mat-button type="submit" (click) = "save1()">Save</button>
</form>
</div>
</div>
component.ts
t1(i1){
if(this.i1.isChecked){
document.getElementById("i1m").style.display = "block";
} else{
document.getElementById("i1m").style.display = "none";
}
}
close1(){
document.getElementById("i1m").style.display = "none";
}
save1(){
document.getElementById("i1m").style.display = "none";
}
I want to enable the textbox in formgroup2 with id m2 only when the check box i2 in formgroup1 is checked and display formgroup2 with m2 textbox.if i1 is checked the formgroup2 should be displayed without m2 textbox. please guide me through this. Thanks in advance.
Edit: my i1FormGroup(FormGroup2) is a a pop up modal which pop up for each checkbox checked in f1FormGroup(FormGroup1) individually. Based on the checkbox checked the inputs are enabled or disabled. The other input values remain same when entered once.
I added a StackBlitz and explained briefly in the comments in the App.components.ts page at the bottom. Please check it. StackBlitz
Upvotes: 2
Views: 4668
Reputation: 73357
First of all. Don't use ngModel
with reactive forms. Secondly, don't manipulate the DOM. Angular usually have own tools for doing what you want. In this case, I've gone all reactive, and based on the checkbox status, you can call disable()
or enable()
on the formcontrols. Here is a sample:
constructor(private fb: FormBuilder) {
// form with checkboxes
this.f1FormGroup = this.fb.group({
cb1: [false],
cb2: [false]
})
// form with inputs
this.i1mFormGroup = this.fb.group({
inp1: [''],
inp2: ['']
})
// listen to the changes of the checkboxes and disable/enable when wanted
this.f1FormGroup.valueChanges.subscribe((value) => {
value.cb1 ? this.i1mFormGroup.get('inp1').disable() : this.i1mFormGroup.get('inp1').enable()
})
}
Also then add formControlName
to the template, and remove ngModel
.
Here's a demo: StackBlitz
Upvotes: 3