Angular:有关以编辑形式进行数据绑定的问题

问题描述 投票:0回答:1

我正在构建一个编辑表单,该表单必须在初始化时填充输入字段。

这是组件ts文件。

import { Component, OnInit, HostBinding } from '@angular/core';
import { Collection } from 'src/app/models/collection';
import { CollectionsService } from '../../services/collections.service';
import { ActivatedRoute, Router } from '@angular/router';

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

  @HostBinding('class') classes = 'row';

  cta: string; // Form CTA text

  collection: Collection = {
    Name: '',
    Description: ''
  };

  edit: boolean = false;

  constructor(private collectionsService: CollectionsService, private router: Router, private activatedRoute: ActivatedRoute) { }

  ngOnInit(): void {
    this.cta = 'Add collection';
    const params = this.activatedRoute.snapshot.params;
    if(params.id) {
      this.cta = 'Edit collection';
      this.collectionsService.getCollection(params.id)
        .subscribe(
          res => {
            this.collection = res;
            this.edit = true;
          },
          err => console.log(err)
        )
    }
  }

这是组件html文件:

<div class="col-md-8 offset-md-2">
    <div class="card">
        <div class="card-body">
            <form ngForm>
                <div class="form-group">
                    <input type="text" name="name" [(ngModel)]="collection.Name" placeholder="Collection name" class="form-control" autofocus>
                </div>
                <div class="form-group">
                    <textarea name="description" [(ngModel)]="collection.Description" placeholder="Collection description" rows="2" class="form-control"></textarea>
                </div>
                <button class="btn btn-success btn-block" (click)="createNewCollection()">{{cta}}</button>
            </form>
        </div>
    </div>
</div>

这是数据模型:

export interface Collection {

    Name?: string,
    Description?: string,
    OwnerID?: number

};

到编辑表单的路径是collections / edit /:id。当我导航到该URL时,可以在浏览器控制台中看到正确提取了数据。但是,我无法在相应的输入字段中显示它。

顺便说一句,POST方法可以正常工作。

我正在使用Angular 9.1.3。

angular angular-forms
1个回答
0
投票
this.activatedRoute.params.subscribe((params) => {
if(params.id) {
      this.cta = 'Edit collection';
      this.collectionsService.getCollection(params.id)
        .subscribe(
          res => {
            this.collection = res;
            this.edit = true;
          },
          err => console.log(err)
        )
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.