0
votes

I know this's been asked many times before. But I cannot find a solution that works for me.

I have a template driven form with a control which marked as required and passed via ngTemplateOutlet. Form is valid even when I don't have value on the control.

Tried all possible

  viewProviders: [{ provide: ControlContainer, useExisting: NgForm }],

AND

  viewProviders: [{
       provide: ControlContainer,
       useFactory: (container: ControlContainer) => container,
       deps: [[new SkipSelf(), ControlContainer]],
       }]

but no luck

If you could make this Stackbliz work, that would be awesome

https://stackblitz.com/edit/angular-xm3nf7

Note: I cannot put the template inside the form as there are other parts accessing it.

1
Well this cloud be an angular bug or feature, because angular is not even updating the form's controls. But a work around is with reactive forms. - German Meza

1 Answers

1
votes

I Supouse your form don't know about the ngModel of the ngTemplate. A work arround is using ViewChildren to check all the NgModels in the pages are valid or not. see stackblitz

@ViewChildren(NgControl) list: QueryList<NgControl>;
  lastName: string;
  yet=false
  get invalid() {
    let invalid = false;
    if (this.list) {
      this.list.forEach(x => {
        invalid = invalid || x.invalid
      })
    }
    return invalid
  }
  ngOnInit()
  {
    setTimeout(()=>{
      this.yet=true
    })
  }

<button [disabled]="yet && invalid"  (click)="actionConfirmed()"> Confirm  </button>

NOTE the "strange" yet is to avoid AfterChecked error