2

Assuming the template has code snippet like this:

<form #myForm="ngForm">
   <md-input-container>
     <input mdInput name="address" [formControl]="addressCtrl" [(ngModel)]="address" required>
   </md-input-container>
</form>

And the component has something like this:

export class AddressComponent {
   @ViewChild("myForm")
   myForm: NgForm;

   addressCtrl = new FormControl();
   address: string;

   constructor() {}

   validate() {
      this.addressCtrl.markAsTouched();
      console.log("Is address valid? " + this.addressCtrl.valid);
      console.log("Is myForm valid? " + this.myForm.form.valid);
   }
}

The validate() is invoked by some other action, which aim at triggering the form validation programmatically.

However, in the console log, it shows that the addressCtrl is invalid while myForm is still valid.

Anyone knows how to update myForm status to be invalid if any of its child control is invalid?

Thanks!

2
  • I'd have to look at the source to give a better answer, but a better way to debug may actually be to add the check in your Html, perhaps add {{myForm | json}} to your Html, just in case the flag to flip the form validity happens after the console.log statement. Commented Jul 14, 2017 at 1:04
  • I've tried, but value is always true. Commented Jul 14, 2017 at 3:29

1 Answer 1

1

You are using formControl directive which is designed to be standalone so it doesn't register itself in the parent formGroup. If you show the controls of the group you will see the the control you created is not part of that group:

console.log(this.form.value);       // {}
console.log(this.myForm.controls);  // undefined

You need to use formControlName directive, but for that you will have to create a formGroup in the class:

  addressCtrl = new FormControl();
  group = new FormGroup({address: this.addressCtrl});

  validate() {
    console.log('Is address valid? ' + this.addressCtrl.valid); // false
    console.log('Is myForm valid? ' + this.group.valid);        // false
  }

And HTML:

<form [formGroup]="group">
   <md-input-container>
     <input mdInput name="address" formControlName="address" [(ngModel)]="address" required>
   </md-input-container>
</form>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.