I have created a model-driven form in Angular 2, and I need one of the input fields to only show up if a specific checkbox is unchecked. I was able to achieve this using *ngIf directive. Now, my question is how can I make that input field required only when the checkbox is unchecked? In Angular 1.x, I could easily do this by using ng-required="condition" in the view.
Below is the HTML code:
// The Checkbox
<div class="checkbox col-sm-9">
<label>
<input type="checkbox" id="getCompanyAddress" style="cursor: pointer;" [formControl]="form.controls['address']">Use the company address
</label>
</div>
// The Optional Input Field:
<div *ngIf="form.value.address == false" class="form-group" [ngClass] = "{'has-error':!form.controls['address'].valid && form.controls['address'].touched}">
<label for="add_gestion_adress" class="col-sm-3 control-label">Address
</label>
<div class="col-sm-9"><textarea rows="1" id="add_gestion_adress" class="form-control" name="add_gestion_adress" [formControl]="form.controls['address']"></textarea>
</div>
</div>
// Model Code:
form: FormGroup;
constructor(fb:FormBuilder){
this.form = fb.group({
'name': [null,Validators.compose([Validators.required, Validators.minLength(1)])],
'type': ["en gros",Validators.compose([Validators.required, Validators.minLength(2)])],
'person':[null,Validators.compose([Validators.required, Validators.minLength(1)])],
'address':[false,Validators.compose([Validators.minLength(1)])],
'locality':[null, Validators.compose([Validators.required])],
'county':[null,Validators.compose([Validators.required])],
'country':[null,Validators.compose([Validators.required])]
})
}