'Set Formgroup valid or invalid angular 7

I have one form where I need to set the fields to valid or invalid, because I want to edit the user, but the button stay disabled

edit.component

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

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

when I'll go to the page edit I would like abilit the button I need to set invalid the form

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

for example

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

enter image description here

this is my page to edit item, but the formgroup is invalid even with the field filled in, why ?



Solution 1:[1]

What you're doing in the HTML is correct. Maybe it's better to set it as [disabled]="formGroup.invalid".

I don't understand your example if statement. What's your question exactly ?

Solution 2:[2]

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'
    });
  }

I think you have no need to write if and else condition because reactive form is give you form status if you set value with right manner.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IamMowgoud
Solution 2 Abhishek