I'm using Angular version 6.0.7.
I have four <input>
fields where the latest three is only required if the first one is provided. I'm trying to make it working by using [attr.required]="<boolean here>"
and [required]="<boolean here>"
, but the required attribute is not removed from the input when the binding value is false.
<div class="col">
<h3 class="mb-3">Ensino superior</h3>
<div class="form-group">
<label for="ad-higher-education-institution">Nome da instituição</label>
<input
[(ngModel)]="client.academic_data.higher_education.institution"
id="ad-higher-education-institution"
name="ad-higher-education-institution"
type="text"
class="form-control">
</div>
<div class="row">
<div class="col form-group">
<label for="ad-higher-education-city">Cidade</label>
<input
[(ngModel)]="client.academic_data.higher_education.city"
[attr.required]="client.academic_data.higher_education.institution && client.academic_data.higher_education.institution.length > 0"
id="ad-higher-education-city"
name="ad-higher-education-city"
type="text"
class="form-control">
</div>
<div class="col form-group">
<label for="ad-higher-education-state">Estado</label>
<input
[(ngModel)]="client.academic_data.higher_education.state"
[attr.required]="client.academic_data.higher_education.institution && client.academic_data.higher_education.institution.length > 0"
id="ad-higher-education-state"
name="ad-higher-education-state"
type="text"
class="form-control">
</div>
</div>
<div class="form-group">
<label for="ad-higher-education-course">Curso</label>
<input
[(ngModel)]="client.academic_data.higher_education.course"
[attr.required]="client.academic_data.higher_education.institution && client.academic_data.higher_education.institution.length > 0"
id="ad-higher-education-course"
name="ad-higher-education-course"
type="text"
class="form-control">
</div>
<div class="form-group">
<label for="ad-high-school-conclusion-year">Ano de conclusão</label>
<input
[(ngModel)]="client.academic_data.higher_education.conclusion_year"
[attr.required]="client.academic_data.higher_education.institution && client.academic_data.higher_education.institution.length > 0"
id="ad-higher-education-conclusion-year"
name="ad-higher-education-conclusion-year"
type="text"
class="form-control"
mask="0*">
</div>
</div>
</div>
How to remove the required
attribute when the first input is not filled?
This is the input when the first is filled:
<input
class="form-control ng-valid ng-dirty ng-touched"
id="ad-higher-education-city" name="ad-higher-education-city" type="text" ng-reflect-name="ad-higher-education-city" ng-reflect-model=""
required="true">
And this is the input when the first is NOT filled:
<input
class="form-control ng-valid ng-dirty ng-touched"
id="ad-higher-education-city" name="ad-higher-education-city" type="text" ng-reflect-name="ad-higher-education-city" ng-reflect-model=""
required>