Angular:编辑表单中的数据绑定问题



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

这是组件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。

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)
)
}
})

最新更新