【问题标题】:formControlName is not rendered when creating control dynamically in Angular在 Angular 中动态创建控件时不呈现 formControlName
【发布时间】:2021-12-01 00:56:58
【问题描述】:

我正在努力创建一个表单,该表单将通过 API 提供控件。表单呈现没有任何问题。但是,formControlName 属性在呈现时从 HTML 中丢失。这会导致mat-datepicker 出现问题。因为它要求formControlName 与控件相关联

这是我的模板

      <div *ngFor="let item of list; let i=index;">
        <mat-form-field appearance="fill">
          <mat-label>{{item.control["Caption"]}}</mat-label>

          <input *ngIf="(item.control['Type'] == "Text")" matInput formControlName="{{item.key}}" >
          

          <input *ngIf="item.control['Type'] == 'Date'" matInput [matDatepicker]="i" placeholder="DD/MM/YYYY" [formControlName]="item.key"  >
          <mat-datepicker-toggle *ngIf="item.control['Type'] == 'Date'" matSuffix [for]="i"></mat-datepicker-toggle>
          <mat-datepicker *ngIf="item.control['Type'] == 'Date'" #i></mat-datepicker>


        </mat-form-field>

      </div>
    </form>

现在的问题是日期控件已呈现,但在单击控件上的日历图标时未出现日历弹出窗口。但是,如果我在控件中手动输入日期,则它会正确提交。

我在这里错过了什么。我需要能够将mat-datepicker 与呈现的任何和所有日期控件绑定。

【问题讨论】:

    标签: angular typescript angular-material angular-directive


    【解决方案1】:

    像这样更新你的模板:

    <div *ngFor="let item of list; let i=index">
        
        <mat-form-field appearance="fill">
        
          <mat-label>{{item.control["Caption"]}}</mat-label>
    
          <input *ngIf="item.control['Type'] == 'Text'" matInput [formControlName]="item.key" >
          
          <ng-container *ngIf="item.control['Type'] == 'Date'">
            <input  matInput [matDatepicker]="i" placeholder="DD/MM/YYYY" [formControlName]="item.key"  >
            <mat-datepicker-toggle matSuffix [for]="i"></mat-datepicker-toggle>
            <mat-datepicker #i></mat-datepicker>
          </ng-container>
    
        </mat-form-field>
    
     </div>
    

    这里我使用了ng-container,因为它不会在 DOM 中添加额外的标签,你也可以在这里使用div,但这会在 DOM 中添加新的标签。您可以检查元素并查看差异。 你可以阅读更多关于ng-containerhere

    【讨论】:

    • 谢谢。这解决了我的问题。您能否评论一下在这种情况下如何或为什么需要 ng-container?可能是某个文档/讨论的链接?
    • 您使用的是 diff ngIf,我认为这是导致问题的原因,您只需将您的 inputmat-datepicker-togglemat-datepicker 一起渲染。还用更多描述更新了我的答案
    猜你喜欢
    • 2018-09-02
    • 2012-04-29
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2016-08-23
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多