Reputation: 8940
I have a Modell driven Form in Angular which contains the following input field (among other input fields that do work properly (input
):
<div class="form-group">
<textarea class="form-control" type="text" id="message" name="message" placeholder="Message" rows="7" formControlname="message"></textarea>
<small [hidden]="contactForm.controls['message'].valid || (contactForm.controls['subject'].untouched && !submitted)">
Please enter a Message
</small>
</div>
In the component I did define some validation using:
ngOnInit() {
this.contactForm = new FormGroup({
message: new FormControl('', [Validators.required]),
});
}
But the message does never get Valid (The HTML does allways show Please enter a Message
)
While the following Unit Tests do work as expected:
it('message control should not be valid without input', () => {
const messageControl: AbstractControl = component.contactForm.controls['message'];
messageControl.setValue('');
expect(messageControl.valid).toBe(false);
});
it('message control should be valid with any input', () => {
const messageControl: AbstractControl = component.contactForm.controls['message'];
messageControl.setValue('Some Message');
expect(messageControl.valid).toBe(true);
});
Gave the expected results. Why is the Validation not working properly when I do input a Value manually?
Upvotes: 1
Views: 5453
Reputation: 2486
Bind your form inside a formgroup first
<div class="form-group" [formGroup]="contactForm">
<textarea class="form-control" type="text" id="message" name="message" placeholder="Message" rows="7" formControlname="message"></textarea>
<small [hidden]="contactForm.controls['message'].valid || (contactForm.controls['subject'].untouched && !submitted)">
Please enter a Message
</small>
Upvotes: 2