Home > Mobile >  Access form inside ng-template in a template driven form
Access form inside ng-template in a template driven form

Time:03-31

<form #f="ngForm">
  <ng-container *ngTemplateOutlet="template"></ng-container>
  {{f.controls.formInput.value}} // gives error
  <ng-template #template>
    <div >
      <input ngModel name="formInput">
    </div>
  </ng-template>
</form>

As you can see, I'm accessing formInput after the ng-container but getting an error. What am I doing wrong?

CodePudding user response:

In Angular v13 it's working for me

<form #f="ngForm">
  <ng-container *ngTemplateOutlet="template"></ng-container>
  {{ f?.controls?.['formInput']?.value }}
  <ng-template #template>
    <div >
      <input #formInput="ngModel" ngModel name="formInput">
    </div>
  </ng-template>
</form>

CodePudding user response:

By default it has nothing to display, it's empty. You have not bound the the input to anything. The form and value currently as it is, exists only in template. If you add [(ngModel)]="input" and input = 'test' to TS it would have something.

Template: 
<form #f="ngForm">
  <ng-container *ngTemplateOutlet="template"></ng-container>

  <ng-container *ngIf="f.controls.formInput?.value">
    {{f.controls.formInput.value}}
  </ng-container>

  <ng-template #template>
    <div >
      <input [(ngModel)]="input" name="formInput">
    </div>
  </ng-template>
</form>
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  input = 'test';

  ngOnInit() {}
}

Working example: https://stackblitz.com/edit/angular-ivy-q9usk3?file=src/app/app.component.html

  • Related