【问题标题】:Dynamic form with ContentChildren带有 ContentChildren 的动态表单
【发布时间】:2020-11-16 02:59:53
【问题描述】:

我正在尝试使用 ContentChildren 创建一个动态表单,它已经完成,但是我有 2 个问题

  1. Without Material:提交时无法捕获输入值,不知道怎么做
  2. 使用 Material:我无法捕获对输入的引用,添加“mat-form-field”会使事情变得复杂。

我在 stackblitz 中留下了 example。谢谢!

【问题讨论】:

    标签: angular angular-material angular2-forms


    【解决方案1】:

    为了捕获和监视输入值,我建议您将 ngModel 指令添加到动态表单内的所有 input 控件中。这将自动为每个input 创建一个FormControl 实例,您可以将其添加到动态FormGroup

    注意:您也可以通过访问inputElement.value 来获取输入值,但是 您必须收听input 事件才能观察变化

    html

    <filter-form (onSubmit)="onSubmit($event)">
        <input type="text" placeholder="0.00" propertyName="1" ngModel/>
        <input type="text" placeholder="0.00" propertyName="2" ngModel/>
        <input type="text" placeholder="0.00" propertyName="3" ngModel/>
        <mat-form-field>
            <input matInput type="text" placeholder="0.00" propertyName="4" ngModel/>
        </mat-form-field>
    </filter-form>  
    

    您可以通过将 NgModel 实例注入到您的自定义指令中来获取它:

    @Directive({
      selector: "input"
    })
    export class FocusDirective {
    
      @Input() propertyName: string;
    
      constructor(public ngModel: NgModel) {}
    }
    

    现在,您可以将 FormControl 实例添加到您的 formGroup:

    ngAfterContentInit(): void {
      console.log("ngAfterContentInit::input is: ", this.items);
      this.items.toArray().forEach(x => {
        this.formGroup.addControl(
          x.propertyName,
          x.ngModel.control <--------------------------- this one
        );
      });
    }
    

    为了获得所有ContentChildren,无论嵌套级别如何,您都必须使用descendants 选项:

    @ContentChildren(FocusDirective, { descendants: true }) items: QueryList<FocusDirective>;
    

    Forked Stackblitz

    【讨论】:

      猜你喜欢
      • 2016-12-03
      • 2010-09-26
      • 2019-09-21
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 2023-02-03
      • 2015-11-08
      • 2013-10-14
      相关资源
      最近更新 更多