5

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 ?

Rafael Moura
  • 1,247
  • 2
  • 14
  • 26
  • check this : https://stackoverflow.com/questions/53626704/angular-6-required-only-one-field-from-many-fields-reactive-form – CruelEngine Dec 14 '18 at 05:12

2 Answers2

0

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 ?

IamMowgoud
  • 308
  • 4
  • 13
  • Firts, I'm get user and set in value inpu, this is page to edit, all right, but formgroup continue valid false so the button stay desabled – Rafael Moura Dec 14 '18 at 03:14
  • 1
    Do not set value using `[value]='some value`. Use `form.patchValue({control:value})` or `formControl.patchValue(value)` to set the values for a control – Sachin Gupta Dec 14 '18 at 03:35
0

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.

Abhishek
  • 1,742
  • 2
  • 14
  • 25