Rafael Hernández
Rafael Hernández

Reputation: 364

How to get the data of an object on a form from a service?

I have a list of items each one with a button to see each item on other form. all of my code works but I dont know how to show the item on the form for edit it.

<div class="col-lag-12">


  <ul class="list-group">
    <li class="list-group-item" *ngFor="let book of books">
      <div class="avatar_book">
        <img src="{{ url + 'avatar/' + book.image }}" alt="">
      </div>
    <h4>
      <a [routerLink]="['/inicio']">
        {{book.title}}
      </a>
    </h4>
    <p>{{book.description}}</p>
    <p>{{book.author}}</p>
    <p>{{book.stock}}</p>
    <p>{{book.price}} $</p>
    <a [routerLink]="['/updatebook', book._id]"  class="btn btn-primary float-right">update</a>

   </li>
  </ul>
</div>

updatebook.component

the form to show the item is reactive

<form autocomplete="off" [formGroup]="forma" (ngSubmit)="onSubmit()">
  <div>

    <div class="form-group row">
      <label class="col-2 col-form-label"
      >title</label>
      <div class="col">

        <input class="form-control"
               type="text"
               placeholder="title"
               formControlName="title"
               [class.is-invalid]="titleNoValido"
               >
         <small *ngIf="titleNoValido" class="text-danger">
          write the name
        </small>
      </div>
    </div>

    <div class="form-group row">
      <label class="col-2 col-form-label"
      >description</label>
      <div class="col">

    <textarea  class="form-control" rows="8" cols="80"

               placeholder="description"
               formControlName="description"
               [class.is-invalid]="descripcionNoValido">
               </textarea>

        <small *ngIf="descripcionNoValido" class="text-danger">
          write the name
        </small>
      </div>
    </div>

export class UpdatebookComponent implements OnInit {
  forma   : FormGroup;
  public book: Book;
  public afuConfig;
  public url;
  public token;
  public data;
  public status;
  selectedFile: File = null;
  public id;
  public idBook;
//  public title;
  constructor(
    private fb: FormBuilder,
    private userservice: UserService,
    private bookservice: BookService,
    private http: HttpClient,
    public snackBar: MatSnackBar,
    private activatedRoute: ActivatedRoute,
    private route: ActivatedRoute,
    private router: Router,
  ) {
    this.crearFormulario();
    this.activatedRoute.params.subscribe( params =>{
      console.log(params);
  //    console.log(this.book.id);
    })

    this.getBook();
    //this.book = new Book(this.book.title, this.book.description, this.book.author, this.book.image, this.book.stock, this.book.price);
    this.afuConfig = {
        multiple: false,
        formatsAllowed: '.jpg, .jpeg, .png, .gif',
        maxSize: "50",
        uploadAPI:{
          url: this.url+'save',
          headers:{
            'Authorization': this.token
          }
        },
        theme: 'attachPin',
        hideProgressBar: false,
        hideResetBtn: true,
        hideSelectBtn: false,
        attachPinText:'Sube la imagen'
    };

  }

  get titleNoValido() {
  return this.forma.get('title').invalid && this.forma.get('title').touched
}

  get descripcionNoValido() {
    return this.forma.get('description').invalid && this.forma.get('description').touched
  }

  get authorNoValido() {
  return this.forma.get('author').invalid && this.forma.get('author').touched
}

  get priceNoValido() {
    return this.forma.get('price').invalid && this.forma.get('price').touched
  }

  get stockNoValido() {
    return this.forma.get('stock').invalid && this.forma.get('stock').touched
  }



  crearFormulario() {

  this.forma = this.fb.group({
    title  : ['', [ Validators.required, Validators.minLength(5) ]  ],
    description : ['', Validators.required ],
    author : ['', Validators.required ],
    price : ['', Validators.required ],
    stock : ['', Validators.required ],
    image : ['', Validators.required ]

  });


}


avatarUpload(data)
{

  let data_obj = JSON.parse(data.response);
  this.book.image = data_obj.book.image;
  console.log(this.book.image);
}

  ngOnInit(): void {
  }

getBook()
{
  this.route.params.subscribe(params =>{
    let id = params['id'];
    this.bookservice.getBook(id).subscribe(
      response =>
      {
        if(!response.book)
        {
          this.router.navigate(['/pruebabook']);
        }
        else
        {
          this.book = response.book;
          console.log(this.book);
        }
      }
    )
  });
}

book.service

  getBook(bookId):Observable<any>
  {
    return this.http.get(this.url+'book/'+bookId);
    console.log(bookId);
  }

But how to show on updatebook.component in the reactive form the value of the item?

Upvotes: 0

Views: 486

Answers (3)

Mohammed Ismail
Mohammed Ismail

Reputation: 308

crearFormulario function should always do creating and Initialising Reactive Forms.

crearFormulario() {
  this.forma = this.fb.group({
    title: ['', [Validators.required, Validators.minLength(5)]],
    description: ['', Validators.required],
    author: [ '', Validators.required],
    price: ['', Validators.required],
    stock: ['', Validators.required],
    image: ['', Validators.required]
  });
}

According to Angular Documentaion. There are two ways to update the model value:

  • Use the setValue() method to set a new value for an individual control. The setValue() method strictly adheres to the structure of the form group and replaces the entire value for the control.

  • Use the patchValue() method to replace any properties defined in the object that have changed in the form model.

The most recommended way to update large data model for Reactive Forms is to use patchValue()

 {
      this.book = response.book;
      console.log(this.book);
      this.forma.patchValue(response.book) //here
    }

Upvotes: 0

Kamran Khatti
Kamran Khatti

Reputation: 4127

You can assign each form field value when you initializing the form, call crearFormulario() method inside getBook() and pass the book response.

crearFormulario(book) {
  this.forma = this.fb.group({
    title: [book ? book.title : '', [Validators.required, Validators.minLength(5)]],
    description: [book ? book.description : '', Validators.required],
    author: [book ? book.author : '', Validators.required],
    price: [book ? book.price : '', Validators.required],
    stock: [book ? book.stock : '', Validators.required],
    image: [book ? book.image : '', Validators.required]
  });
}

and call crearFormulario() inside

    {
      this.book = response.book;
      console.log(this.book);
      crearFormulario(this.book); //here
    }

Hope this works.

Upvotes: 1

Rafael Hern&#225;ndez
Rafael Hern&#225;ndez

Reputation: 364

this worked for me

{
          this.book = response.book;
           this.forma.controls['title'].setValue(response.book.title);
           this.forma.controls['description'].setValue(response.book.description);
           this.forma.controls['author'].setValue(response.book.author);
           this.forma.controls['stock'].setValue(response.book.stock);
           this.forma.controls['price'].setValue(response.book.price);
          console.log(this.book);
        }

Upvotes: 0

Related Questions