Kumar Gaurav
Kumar Gaurav

Reputation: 1317

Angular 4 validation with default values

I am struggling with validation in angular 4. I have a component which gets populated by an input provided by parent component. I have put validation on a particular textbox which gets populated by input object (given by parent component). Angular consider the input as error below is my markup

<mat-form-field class="fill-control">
    <input matInput placeholder="link" value="{{feed.link}}" formControlName="link" required>
</mat-form-field>
<mat-error *ngIf="!moderateFeedForm.controls['link'].valid && moderateFeedForm.controls['link'].touched">
    Please enter a valid url
</mat-error>

in constructor of my component I have below code

this.moderateFeedForm = this.fb.group({
      'link':['',Validators.compose([Validators.required])]],
})

In my form I have many other fields, and behavior is same for all of them, i have just put one here. There is no compilation error but when I focus and un-focus the textbox I get below error

"Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'null'. Current value: 'mat-error-0'"

To me it looked like as if validations gets applied before values get populated or somehow validators doesn't know about these values. when i simply edit the values and put the same value again validation gets passed.

What's wrong happening here?

Upvotes: 1

Views: 4384

Answers (3)

Kumar Gaurav
Kumar Gaurav

Reputation: 1317

Finally i figured out. I was giving wrong initial value. In my component i had to initialize it as below

this.form= this.fb.group({[initialval], [validations...]})

Upvotes: 0

oflad
oflad

Reputation: 78

Try replacing your *ngIf="!moderateFeedForm.controls['link'].valid && moderateFeedForm.controls['link'].touched" with ``*ngIf="invalid('link')"`.

Then in your component.ts file add a method:

invalid(control) {
    return !moderateFeedForm.controls[control].valid && 
    moderateFeedForm.controls[control].touched;
}

You can also remove the Validators.compose clause from your code and simply have 'link':['',[Validators.required]]

Upvotes: 1

Mohamed Gara
Mohamed Gara

Reputation: 2935

In the template, you should remove the required directive from the input tag.

Upvotes: 0

Related Questions