【问题标题】:Formcontrol disable input value previewFormcontrol 禁用输入值预览
【发布时间】:2021-02-26 10:00:47
【问题描述】:

我做了一个步进器,我想在选择中输入一个默认值。为此,我使用两种方式绑定[(value)] 属性。它奏效了。

但只要我添加了[formControl] 属性,输入值就会消失。它仍然以编程方式存在,但不再出现在下拉列表中。

这是一个步骤示例:

  <mat-step state="class" [stepControl]="firstFormControl">
    <form [formGroup]="firstFormGroup">
      <ng-template matStepLabel>Foo Label</ng-template>
      <mat-form-field>
        <mat-label>Foo Label</mat-label>
        <mat-select [(value)]="myVar" [formControl]="firstFormControl" required>
          <mat-option *ngFor="let i of customCollection" [value]="i">
            {{i.name}}
          </mat-option>
        </mat-select>
      </mat-form-field>
      <div>
        <button mat-button matStepperNext>Next</button>
      </div>
    </form>
  </mat-step>

这是表单定义:

public firstFormGroup: FormGroup;
public firstFormControl: FormControl;
this.firstFormControl = new FormControl('', Validators.required);
this.firstFormGroup = this._formBuilder.group({
   firstCtrl: ['', Validators.required]
});

[(value)] 属性中使用的 myVar 值完全位于表单外部,仅引用 customCollection 元素之一。

知道如何解决这个问题吗?非常感谢 !凯夫'

【问题讨论】:

    标签: angular angular-material dropdown angular-forms angular11


    【解决方案1】:

    您不需要在单个控件上同时使用模板驱动表单和反应式表单。

    您可以选择退出响应式表单控件,以便在组件代码中访问它。 所以删除该部分如下

    &lt;mat-select [formControl]="firstFormControl"&gt;

    在您的组件中,您可以根据需要设置此控件

    get myVar(): any {
       return this.form.get('firstFormControl').value;
    }
    

    firstFormControl 定义为在 FormGroup 对象内部。比如在ngInit方法里面

      this.form = this.formBuilder.group({'firstFormControl', ['', [Validators.required]]});
    

    【讨论】:

    • 感谢您的回答,继续,如何输入下拉菜单中显示的默认值?在 firstFormControl 中输入它会完成这项工作吗?
    • 如果我理解正确,我们应该在表单上使用“setValue()”方法吗?我很困惑,因为我这里的对象是由一个 ID 和一个名称组成的。所以我很难正确输入,以便以编程方式使用 id 并将名称显示给用户。
    【解决方案2】:

    对于那些到达那里的人。

    我误用了 formcontrol 和 formGroup。

    我已删除 firstFormControl 并在 mat-select 行中使用属性 formControlName="firstCtrl"

    我已删除 [(value)]=myVar 属性,使其处于完全反应式表单并停止使用模板驱动表单。

    你可以从打字稿中输入一个默认值

    this.firstFormGroup.get('firstCtrl').setValue( this.customCollection[2].id );
    

    再见!

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 2020-11-24
      • 1970-01-01
      • 2018-09-21
      • 2022-01-18
      • 2020-10-01
      • 2013-05-16
      • 2020-04-19
      • 1970-01-01
      相关资源
      最近更新 更多