Angular 将Formgroup设置为有效或无效

Angular 将Formgroup设置为有效或无效,angular,Angular,我有一个表单,需要将字段设置为有效或无效,因为我想编辑用户,但按钮保持禁用状态 编辑组件 ngOnInit() { this.getForm(); this.getRole(); console.log(this.formGroup.valid) } getForm() { this.formGroup = this.formBuilder.group({ name: ['', Validators.required], label: ['', Validators.

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

编辑组件

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>


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

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

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

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>

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

首先,我是get user并在值inpu中设置,这是要编辑的页面,好吧,但formgroup continue valid false使按钮保持desabledDo未使用
[值]='some value
设置值。使用
form.patchValue({control:value})
formControl.patchValue(value)
设置控件的值检查此项:
<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>
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'
    });
  }