【问题标题】:Access form inside ng-template in a template driven form在模板驱动的表单中访问 ng-template 内的表单
【发布时间】:2022-08-16 14:45:09
【问题描述】:
<form #f=\"ngForm\">
  <ng-container *ngTemplateOutlet=\"template\"></ng-container>
  {{f.controls.formInput.value}} // gives error
  <ng-template #template>
    <div class=\"reusable-control\">
      <input ngModel name=\"formInput\">
    </div>
  </ng-template>
</form>

如您所见,我在ng-container 之后访问formInput,但出现错误。我究竟做错了什么?

  • 问题可能在于您的模型在 ngForm 范围内是不可见的,这就是您收到错误 angular.io/guide/… 的原因
  • 了解模板变量。但是如何将表单控件formInput 关联到外部表单@kalit?

标签: angular angular-forms


【解决方案1】:

在 Angular v13 中,它对我有用

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

【讨论】:

    【解决方案2】:

    默认情况下,它没有可显示的内容,它是空的。您没有将输入绑定到任何东西。目前的形式和价值,只存在于模板中。如果您将[(ngModel)]="input"input = 'test' 添加到TS,它就会有一些东西。

    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 class="reusable-control">
          <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() {}
    }
    

    工作示例:https://stackblitz.com/edit/angular-ivy-q9usk3?file=src%2Fapp%2Fapp.component.html

    【讨论】:

    • 我不想在这里使用 Reactive Form,我的朋友。模板驱动的表单适合我更大的用例。
    • 对不起,我完全忽略了那部分。无论如何,我将它重构为模板驱动的形式。问题发生在您尝试在呈现#template 之前访问控件上的value,实际上将输入保存在值应该在的位置。所以不知何故你必须等到它被渲染才能访问它,否则你最终会得到未定义的。使用*ngIf 可能是一种方法。其他人使用? 发布了类似的想法,以检查道具是否存在。
    • 没有错误,但它也不显示。我希望显示该值。
    • 如果你在那里写了一些东西,那么它就会被显示出来。默认情况下,它没有可显示的内容,它是空的。您没有将输入绑定到任何东西。目前的形式和价值,只存在于模板中。如果您将[(ngModel)]="input"input = 'test' 添加到TS,它就会有一些东西。
    猜你喜欢
    • 2019-04-16
    • 2016-09-02
    • 2017-01-30
    • 2021-01-09
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2020-04-07
    • 2016-04-26
    相关资源
    最近更新 更多