Home > Enterprise >  Input is not showing the Angular´s reactive form value
Input is not showing the Angular´s reactive form value

Time:04-24

I´m building up an Angular basic CRUD app for try new things, but wish to know why this is happening.

I´m trying to get the "post" data and I do from a service, this is working fine, the problem is when I´m setting up the form, show the rest of the values, but not the user ID.

This is the code:

HTML

<div >
    <h1 >Modify register</h1>
    <div >
        <h3 >Modify register</h3>
        <form [formGroup]="editRegisterForm" (ngSubmit)="editRegister()">
            <div >
                <input type="text"  id="userIdInput" formControlName="user" readonly>
            </div>
            <div >
                <textarea  id="titleInput" cols="30" rows="3" placeholder="Write here the title of your post" formControlName="title"></textarea>
            </div>
            <div >
                <select  name="completedSelect" id="comletedSelect" formControlName="completed">
                <option value="default" hidden>Choose an option</option>
                <option value="completed">Completed</option>
                <option value="no completed">Not completed</option>
              </select>
            </div>
            <button type="submit" >Update register</button>
        </form>
    </div>
</div>

TypeScript

 ngOnInit(): void {
    this.registerId = this.route.snapshot.paramMap.get('id');
    this.todosService.getAllRegistersById(this.registerId).subscribe((res: any) => {
      this.editRegisterForm = this.initEditForm(res);
    });
  }

 initEditForm(response: any){
    const { user, title, completed } = response;
    let status;
    completed === true? (status = 'completed'): (status = 'no completed');
    return this.fb.group({
      user: [user, [Validators.required]],
      title: [title, [Validators.required, Validators.maxLength(199)]],
      completed: [status, [Validators.required]]
    });
  }

CodePudding user response:

Try injecting ChangeDetectorRef in constructor and run markforcheck() after form is initialized.

CodePudding user response:

I would suggest a different approach.

  • Don't try to reassign a value to editRegisterForm, but instead inside initEditForm, you can do the following:
      this.editRegisterForm.get('user').setValue(yourUserValue);
      this.editRegisterForm.get('title').setValue(yourTitleValue);
      this.editRegisterForm.get('completed').setValue(yourCompletedValue);

This way you're going to update your FormControl's values. Otherwise your approach is probably causing an issue with change detection and I don't see a point to reassign the value of your FormGroup, when you're just trying to update your field's values and there's an API defined for that.

  • Related