Reputation: 306
I wish to show the input field when "Others" option is selected on dropdown, but can't figure out how to-
Here is my code
<div class="form-group">
<label for="college">College:</label>
<select class="form-control" id="college" ngModel name="college_name" required>
<option>Ajay Kumar Garg Engineering College</option>
<option>Others- Please Specify Below</option>
</select>
</div>
<div class="form-group" *ngIf="showfield">
<label for="name">Enter College Name:</label>
<input type="text" class="form-control" id="name" ngModel name="other_college_name" required>
</div>
showfield = false; is set in .ts file
Upvotes: 5
Views: 36629
Reputation: 18647
In your component take a variable,
selectedValue: string = '';
Just assign selectedvalue
to ngModel
and use that value to display text field.
Also, options needs value attribute
and it needs value to store in ngModel
<div class="form-group">
<label for="college">College:</label>
<select class="form-control" id="college" [(ngModel)]="selectedValue" name="college_name" required>
<option value="college">Ajay Kumar Garg Engineering College</option>
<option value="others">Others- Please Specify Below</option>
</select>
</div>
<div class="form-group" *ngIf="selectedValue == 'others'">
<label for="name">Enter College Name:</label>
<input type="text" class="form-control" id="name" ngModel name="other_college_name" required>
</div>
Upvotes: 12
Reputation: 10934
Your options must have a value associated with them, the selected options value will get set to the model associated with your dropdown select. You can check that for show/hide as follows:
<div class="form-group">
<label for="college">College:</label>
<select class="form-control" id="college" [(ngModel)]="selectedVal" name="college_name" required>
<option value="ajay">Ajay Kumar Garg Engineering College</option>
<option value="others">Others- Please Specify Below</option>
</select>
</div>
<div class="form-group" *ngIf="selectedVal==='others'">
<label for="name">Enter College Name:</label>
<input type="text" class="form-control" id="name" ngModel name="other_college_name" required>
</div>
Upvotes: 0
Reputation:
You can do like so
<div class="form-group">
<label for="college">College:</label>
<select class="form-control" id="college" [(ngModel)]="collegeName" name="college_name" required>
<option value="AKGEC">Ajay Kumar Garg Engineering College</option>
<option value="other">Others- Please Specify Below</option>
</select>
</div>
<div class="form-group" *ngIf="collegeName === 'other'">
<label for="name">Enter College Name:</label>
<input type="text" class="form-control" id="name" ngModel name="other_college_name" required>
</div>
Upvotes: 4