Nick
Nick

Reputation: 480

I can't update the table after adding new values

I'm new to angular, and I'm trying to insert new values and display them in a table. Thus, I have three components, one for listing the information of a user user-list, one for creating the information raws user-form and one for the presentation of these information single-user.

My issue is when I try to insert a new information raw, the table liste doesn't update or refresh it self even I did the redirection to it, and I don't know the raison why. May someone gives me any indication. thanks in advance.

User-list.component.ts:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from '../services/user.service';
import { Subscription, Observable } from 'rxjs';
import { User} from '../model/user.model';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.css']
})
export class UserListComponent implements OnInit, OnDestroy {

  constructor(private router: Router, private userService : UserService ) { }

  userSubscription: Subscription;
  users: Observable<User[]>;

  ngOnInit() {
    this.reloadData();
  }

  reloadData(){
   this.userSubscription = this.userService.getResource("/users").subscribe(
      data =>{
        this.users= data;
        console.log(this.users);
      },
      error => { console.log(error);
      }
   ); 
  }

  ngOnDestroy() { this.userSubscription.unsubscribe(); }

}

User-list.component.html:

<div id="page-wrapper">
  <div class="main-page">
    <div class="tables">
        <app-user-form></app-user-form>
        <div class="table-responsive bs-example widget-shadow" data-example- 
           id="contextual-table"> 
             <table class="table table-hover "> 
          <thead> 
                <tr> 
                    <th>#</th> 
                    <th>Name</th>
                    <th>Age</th>
                    <th>Action</th> 
                </tr> 
           </thead>
              <tbody class="body">
              <ng-container *ngFor="let u of users"> 
                  <tr class="active" 
                    app-single-user
                    [IdUser] =  "u.idUser"
                    [NameUser] = "u.nameUser"
                    [AgeUser] = "u.ageUser"
                  > 
                  </tr>
            </ng-container>
          </tbody> 
        </table> 
        </div>
    </div>
  </div>
</div>

User-form-component.ts

@Component({
  selector: 'app-user-form',
  templateUrl: './user-form.component.html',
  styleUrls: ['./user-form.component.css']
})
export class UserFormComponent implements OnInit {

  userForm: FormGroup;

  constructor(private formBuilder: FormBuilder,
              private router: Router, 
              private userService: UserService
              ) { }

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    this.userForm = this.formBuilder.group({
      nameUser: ['', Validators.required],
      ageUser: ['', Validators.required]
    });
  }

  reInitForm() {
    this.userForm = this.formBuilder.group({
      nameUser: '',
      ageUser: ''
    });
  }

  onSubmit(){
    const formValue = this.userForm.value;
    const newuser = new User(
      formValue['nameUser'],
      formValue['ageUser']
    );
    this.userService.postResource('/users', newUser).subscribe(
      data =>{
        console.log(data)
      },
      error=>{
        console.log(error)
      } 
    );
    this.reInitForm();
    this.router.navigate(['/users']);
  }

}

user-form-component.html:

<div class="table-responsive bs-example widget-shadow" data-example-id="contextual-table">

    <div class="main-page">
    <form [formGroup]="userForm" (ngSubmit)="onSubmit()" class="form-inline">
        <div class="form-group">

            &nbsp;
            <input type="text" class="form-control" id="name"
                   formControlName="nameUser" name="name" required>

          <input type="text" class="form-control" id="age" 
                   formControlName="ageUser" name="age" required>

        </div>
        &nbsp; &nbsp;

        <button type="submit" class="btn btn-success"
            [disabled]="userForm.invalid">Submit</button>
    </form>
    </div>

</div>

I tried the redirect to the same component this.router.navigate(['/users']); in oder to refresh the content of the table but it doesn't work. I appreciate it if someone can give me some hints or indications to solve it. thanks

Upvotes: 1

Views: 1173

Answers (1)

nash11
nash11

Reputation: 8660

As mentioned in the comments, users should be of type User[] since you are assigning the subscribed value to it and navigating to the same component will not cause the component to rerender.

Instead you can use @Output to achieve this. Once you add the newUser, you refresh the data in your parent component(user-list.component.ts).

user-form-component.ts

@Output() submitted = new EventEmitter<void>();

Then on success of your POST API, emit the event

this.userService.postResource('/users', newUser).subscribe(
    data => {
        console.log(data);
        this.submitted.emit();
    },
    error => {
        console.log(error);
    } 
);

In your parent component's template, you need to add this event to your custom component.

user-list.component.html

<app-user-form (submitted)="onSubmit($event)"></app-user-form>

Then in your parent component.

user-list.component.html

onSubmit() {
    this.reloadData();
}

For more information on how to use @Output, see the docs.

Upvotes: 1

Related Questions