FormBuilder
Using FormBuilder
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
paymentForm: FormGroup;
/**
* Used to get a reference to the payment amount field in the template to determine whether or not to display a validation message for the field.
*/
get paymentAmountField() { return this.paymentForm.get('paymentAmount'); }
constructor(private formBuilder: FormBuilder) {
this.paymentForm = this.formBuilder.group({
scheduledDate: new FormControl('', [Validators.required, Validators.pattern(/^\d{1,2}\/\d{1,2}\/\d{4}$/)]),
calendarYear: new FormControl('', [Validators.required, Validators.minLength(4)]),
paymentType: new FormControl('', Validators.required),
comment: new FormControl('')
});
}
// Update values in the form manually
this.paymentForm.patchValue({
scheduledDate: this.paymentDetail.scheduledDate,
calendarYear: this.paymentDetail.calendarYear,
paymentType: this.paymentDetail.paymentType,
comment: this.paymentDetail.paymentReason
},
{ emitEvent: false });
// Update a form element's validator dynamically
this.paymentForm.get('comment').setValidators([Validators.required]);
this.paymentForm.get('comment').updateValueAndValidity();
In HTML
<form [formGroup]="paymentForm">
<label for="paymentAmount" class="font-weight-bold mb-2">Payment Amount *</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" aria-hidden="true">$</span>
</div>
<input id="paymentAmount" type="number" class="form-control" name="paymentAmount"
pattern="^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?$" placeholder="Payment Amount"
aria-label="Payment Amount" formControlName="paymentAmount" title="Payment Amount">
</div>
<div class="mb-2 text-brand-red"
*ngIf="paymentAmountField && paymentAmountField.errors && paymentAmountField.errors.max"
aria-live="assertive">The payment amount must be less than or equal to the total funds available.</div>
<label for="paymentCommentField" class="font-weight-bold mb-2">Comment *</label>
<div class="mb-2">
<div class="form-group">
<textarea id="paymentCommentField" #paymentCommentField class="form-control" name="paymentComment"
title="Comment" rows="5" maxlength="140" name="paymentComment" formControlName="paymentComment"
placeholder="Enter comment">
</textarea>
<div aria-live="polite">{{(140 - paymentCommentField.value?.length)}}</div>
</div>
</div>
</form>