Как я могу получить значение для вставки в форму для редактирования, чтобы обновить запись?

#html #node.js #angular #typescript

#HTML #node.js #angular #typescript

Вопрос:

Сначала у меня есть таблица для отображения всех записей книг, у меня есть кнопка для перехода к редактированию записи, и я хочу отредактировать на editbook.html и когда я нажму кнопку отправить, запись будет обновлена. Могу ли я узнать, как я могу это реализовать?

 <tbody>
    <tr *ngFor="let book of books">
      <td class="td-title">{{book.title}}</td>
      <td>{{book.author}}</td>
      <td>{{book.price}}</td>
      <td>{{book.isbn}}</td>
      <td>{{book.details.pages}}</td>
      <td>{{book.details.language}}</td>
      <td class="td-desc">{{book.description}}</td>
      <td><button type="button"><a [routerLink]="['/editbook/', book.isbn]">Edit</a></button></td>
      <td><button type="button">Delete</button></td>
    </tr>
  </tbody>
 

И теперь я собираюсь отредактировать запись, когда нажму кнопку редактирования.
и моя форма редактирования html

editbook.html

 <div *ngIf="book" class="bookdetail-block">
  <div *ngFor="let bookdetail of book" class="bookdetail">
<h1>Edit Book</h1>
<form [formGroup]="editbookForm" (ngSubmit)="onSubmit()">
    <label>Title: <input type="text" formControlName="title">
        <div *ngIf="submitted amp;amp; editbookForm.controls.title.errors" class="error">
            <div *ngIf="editbookForm.controls.title.errors.required">Required</div>
        </div>
    </label>

    <label>Author: <input type="text" formControlName="author">
        <div *ngIf="submitted amp;amp; editbookForm.controls.author.errors" class="error">
            <div *ngIf="editbookForm.controls.author.errors.required">Required</div>
        </div>
    </label>

    <label>Description: <textarea type="text" formControlName="description"></textarea>
        <div *ngIf="submitted amp;amp; editbookForm.controls.description.errors" class="error">
            <div *ngIf="editbookForm.controls.description.errors.required">Required</div>
        </div>
    </label>

    <label>Page: <input type="number" min="1" max="10000" formControlName="page">
        <div *ngIf="submitted amp;amp; editbookForm.controls.page.errors" class="error">
            <div *ngIf="editbookForm.controls.page.errors.required">Required</div>
        </div>
    </label>

    <label>language:
        <select formControlName="language">
                    <option value="English">English</option>
                    <option value="Traditional Chinese">Traditional Chinese</option>
                    <option value="Simpify Chinese">Simpify Chinese</option>
        </select>
        <div *ngIf="submitted amp;amp; editbookForm.controls.page.errors" class="error">
                <div *ngIf="editbookForm.controls.page.errors.required">Please select one option</div>
        </div>
    </label>
    <br />

    <label>Price: <input type="number" formControlName="price">
        <div *ngIf="submitted amp;amp; editbookForm.controls.price.errors" class="error">
            <div *ngIf="editbookForm.controls.price.errors.required">Required</div>
        </div>
    </label>

    <label>ISBN: <input type="text" formControlName="isbn">
        <div *ngIf="submitted amp;amp; editbookForm.controls.isbn.errors" class="error">
            <div *ngIf="editbookForm.controls.isbn.errors.required">Your name is required</div>
        </div>
    </label>

    <label>Image: <input (change)="onFileSelect($event)" type="file">
        <div *ngIf="imageData" class="error">
            <img [src]="imageData" [alt]="editbookForm.value.name">
        </div>
    </label>

    <label style="display:none">ImageData:
        <!-- <div *ngIf="submitted amp;amp; editbookForm.controls.image.errors" class="error"> -->
            <input type="hidden" id="uploadImage">
        <!-- </div> -->
    </label>

    <input type="submit" value="Update Book" class="cta">

</form>
<div *ngIf="success" class="results">
        <p>The Book is updated into the record.</p>
</div>
</div>
</div>
 

и editbook.ts

 import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { DataService } from '../data.service';
import { ActivatedRoute, Router } from "@angular/router";

interface HTMLInputEvent extends Event {
  target: HTMLInputElement amp; EventTarget;
}
@Component({
  selector: 'app-editbook',
  templateUrl: './editbook.component.html',
  styleUrls: ['./editbook.component.scss']
})
export class EditbookComponent implements OnInit {
  isbn: any;
  book: any;
  editbookForm: FormGroup;
  submitted = false;
  success = false;
  imageData : String;
  constructor(private formBuilder: FormBuilder, private data: DataService, private router: Router, private route: ActivatedRoute) { }

  ngOnInit() {

    this.isbn = this.route.snapshot.paramMap.get("isbn");
    this.data.getOneBook(this.isbn).subscribe(data =>{
      console.log({ data });  //show data
      this.book = data
      //console.log(this.books);
    })
  }

  onFileSelect(event?: HTMLInputEvent){
    console.log("selected file")
    console.log(event)
    let files: any = event.target.files[0];
    console.log(files);

    const reader = new FileReader();
    reader.onloadend = () => {
      var b64 = reader.result.toString();
      let el :any = document.querySelector('#uploadImage');
      el.value = b64;
    }
    reader.readAsDataURL(event.target.files[0]);
  }


  onSubmit() {
    /*
    // upload image
    this.bookForm.reset();
    this.imageData = null;
    */

    this.submitted = true;
    if(this.editbookForm.invalid) {
      return;
    }

    this.data.insertBook(this.editbookForm.controls);
    this.success = true;
  }
}
 

как я могу вставить значение во входные данные html?

Комментарии:

1. Возможно this.data.insertBook , возвращает наблюдаемое, если это так, то подпишитесь на него.

2. Если вы пытаетесь editbook.html заполнить данные строки из своей таблицы, вы хотите передать элемент своему новому компоненту editbook .

Ответ №1:

Не используйте ngFor для вставки значения во входные данные html. используйте метод углового исправления.

Например:

 this.bookForm.patchValue({
    title: this.book.title,
    author: this.book.author
});
 

Вы также можете инициализировать значение в форме:

 this.bookForm({
    title:[this.book.title],
    author:[this.book.author]
});
 

Комментарии:

1. извините, я не знаю, что вы имеете в виду в моем коде

Ответ №2:

Предположим, у вас есть два поля на данный момент ( title и author ), вы заполните другие поля позже, когда убедитесь, что все в порядке.

Начните с простого примера (удалите проверки из HTML на данный момент).

Итак, изначально ваш HTML должен быть примерно таким:

 <form [formGroup]="editbookForm" (ngSubmit)="onSubmit()">
    <label>Title: 
        <input type="text" formControlName="title">
    </label>

    <label>Author: 
        <input type="text" formControlName="author">
    </label>

    <input type="submit" value="Update Book" class="cta">
</form>
 

Тогда у вас OnInit должно быть что-то вроде этого:

 ngOnInit() {
    this.isbn = this.route.snapshot.paramMap.get("isbn");
    if (this.isbn) {
      //Cleaning the form from the previous data
      if (this.editbookForm) this.editbookForm.reset();

      this.data.getOneBook(this.isbn)
        .pipe(take(1))  //To ensure that it will unsubscribe later
        .subscribe((data) => {
          this.book  = data;

          //Filling the form
          this.editbookForm.patchValue({
            title: this.book.title,
            author: this.book.author
          });
        });
    }
  }
 

Если это работает, шаг за шагом добавляйте проверки и другие вещи, как вам нравится.
Примеры:

     <div *ngIf="submitted amp;amp; editbookForm.controls.author.errors" class="error">
        <div *ngIf="editbookForm.controls.author.errors.required">Required</div>
    </div>
 

и

 <div *ngIf="book" class="bookdetail-block">
  <div *ngFor="let bookdetail of book" class="bookdetail">
<h1>Edit Book</h1>
 

и так далее.