【问题标题】:Set Formgroup valid or invalid angular 7设置Formgroup有效或无效角度7
【发布时间】:2018-12-14 02:28:40
【问题描述】:

我有一个表单需要将字段设置为有效或无效,因为我想编辑用户,但按钮保持禁用状态

edit.component

ngOnInit() {
  this.getForm();
  this.getRole();
  console.log(this.formGroup.valid)
}

getForm() {
 this.formGroup = this.formBuilder.group({
   name: ['', Validators.required],
   label: ['', Validators.required],
  });
}

当我进入页面编辑时,我希望能够将我需要的按钮设置为无效的表单

<button type="submit" mat-button color="primary" [disabled]="!formGroup.valid">Alterar</button>

例如

if(user) {
  this.formGroup (invalid)
 } else {
  this.formGroup (valid)
}  

这是我要编辑的页面,但是表单组即使填写了字段也是无效的,为什么?

【问题讨论】:

标签: angular


【解决方案1】:

HTML:

<form [formGroup]="form" fxLayout="column" fxLayoutAlign="center center" fxFlex="50">
      <mat-form-field>
        <input matInput placeholder="Input" formControlName="name">
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="Input" formControlName="label">
      </mat-form-field>
      <button type="submit" mat-button color="primary" [disabled]="!form.valid">Alterar</button>
    </form>

TS:

form: FormGroup;
  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: ['', Validators.required],
      label: ['', Validators.required],
    });
  }
  ngOnInit() {
    this.form.patchValue({
      'name': 'Abhishek',
      'label': 'Dubey'
    });
  }

我认为您无需编写 if 和 else 条件,因为如果您以正确的方式设置值,反应式表单将为您提供表单状态。

【讨论】:

    【解决方案2】:

    您在 HTML 中所做的操作是正确的。 也许最好设置为[disabled]="formGroup.invalid"

    我不明白你的例子 if 语句。你的问题到底是什么?

    【讨论】:

    • 首先,我得到了用户并设置了 value inpu,这是要编辑的页面,好吧, 但 formgroup 继续有效 false 所以按钮保持禁用
    • 不要使用[value]='some value 设置值。使用form.patchValue({control:value})formControl.patchValue(value) 设置控件的值
    猜你喜欢
    • 2017-02-08
    • 2015-09-12
    • 2018-03-11
    • 1970-01-01
    • 2021-05-17
    • 2012-12-11
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    相关资源
    最近更新 更多