【问题标题】:How to use an angular component inside a form group?如何在表单组中使用角度组件?
【发布时间】:2020-12-25 16:02:42
【问题描述】:

我目前正在学习 Angular 并一直在尝试构建表单。

目前我表单中的两个输入属于一个 FormGroup:

    <form name="myForm" #form>
       <input name="username" />
       <input name="email" />
    </form>

我正在尝试使电子邮件输入成为它自己的组件,如下所示:

    <form name="myForm" #form>
       <input name="username" />
       <email-input name="email" />
    </form>

电子邮件输入组件:


    <div>
      <input />
    </div>

当我将电子邮件输入组件添加到表单时,它不像以前那样属于 FormGroup,我的问题是在不改变我实现表单的方式的情况下,如何将我的电子邮件输入组件添加到 #form FormGroup .

谢谢!

【问题讨论】:

    标签: angular forms


    【解决方案1】:
     this.addProductForm = this.fb.group({
          prodCtrl: [''],
          colors: new FormArray([]),
          prodFilterCtrl: [''],
          actual_price: ['']
        });
    
    
    <form [formGroup]="addProductForm" (ngSubmit)="onSubmit()"> 
      <div class="row">
        <div class="col s6">
          <button [mat-dialog-close]="true" mat-raised-button color="primary"
          [disabled]="SaveButtonDisable" (click)="addProduct()" class="save-button">{{'SAVE_BTN' | translate:lang }}</button>
          <button [mat-dialog-close]="true" mat-raised-button color="secondary">{{'BACK_BTN' | translate:lang}}</button>
        </div>
        <!--  [disabled]="productSelect.empty" -->
      </div>
      <mat-dialog-content>
        <div class="common-prod-form-wrapper">
          <div class="row">
            <mat-form-field>
              <mat-select required [formControl]="prodCtrl" placeholder="Select" #productSelect  (selectionChange)="onChangeProduct($event.value)">
                <ngx-mat-select-search [formControl]="prodFilterCtrl" placeholderLabel="Find product..."  ></ngx-mat-select-search>
                <mat-option *ngFor="let product of filteredProducts | async" [value]="product">
                  {{product.product_name}}
                </mat-option>
              </mat-select>
            </mat-form-field>
          </div>
        </div>
      </mat-dialog-content>
        
    
    </form>
    

    【讨论】:

    • 这个解决方案如何解决提问者的问题?
    • 是的@Edric,您可以在 [formControl]="prodCtrl" 中使用 [formGroup]="addProductForm" 在您的情况下
    【解决方案2】:

    您需要将父 formGroup 传递给子组件

    试试这个教程

    https://medium.com/@joshblf/using-child-components-in-angular-forms-d44e60036664

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 2019-03-19
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      相关资源
      最近更新 更多