我正在将Angular 7用于我的Web应用程序,并且在html中具有以下代码:
<div class="form-group col-md-6">
<label for="myDate">My Date</label>
<div class="input-group">
<input
class="form-control"
placeholder="yyyy/mm/dd"
id="myDate"
name="myDate"
[ngModel]="project.myDate | date: 'yyyy/MM/dd'"
ngbDatepicker #d="ngbDatepicker"
tabindex="9">
<div class="input-group-append">
<button class="btn btn-outline-secondary calendar" (click)="d.toggle()" type="button"></button>
</div>
</div>
</div>
调用Web API时,我得到了这样的JSON对象:
{
"id": 11,
"description": "This is a test description",
"budget": 1000,
"myDate": "2020/02/11",
...
}
这是组件代码:
export class ProjectEditComponent implements OnInit {
project: Project;
errorMessage: string;
constructor(private myprojectService: ProjectService) { }
ngOnInit() {
this.myprojectService.getDataById(this.dataId).subscribe(
data => (this.project = data, console.log(JSON.stringify(data))),
error => this.errorMessage = error as any,
);
console.log(this.errorMessage);
}
}
除myDate属性外,所有属性均已正确绑定。
我已经进行了一些研究,并尝试了不同的提议解决方案,但是到目前为止,似乎没人能解决问题。
你们中的任何人都面临类似的事情吗?
答案 0 :(得分:0)
要进行双向绑定,首先应确保已将FormsModule
导入到@NgModule
中的app.module.ts
中。
app.module.ts:
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
//import this.
import { FormsModule } from "@angular/forms";
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule], //register it
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
然后,在html文件中使用[(ngModel)]
:
<div class="form-group col-md-6">
<label for="myDate">My Date</label>
<div class="input-group">
<input
class="form-control"
placeholder="yyyy/mm/dd"
id="myDate"
name="myDate"
[(ngModel)]="project.myDate"
ngbDatepicker #d="ngbDatepicker"
tabindex="9">
<div class="input-group-append">
<button class="btn btn-outline-secondary calendar" (click)="d.toggle()" type="button"></button>
</div>
</div>
</div>
我删除了该管道,因为与之一起使用两种方式的bindind给了我错误。检查thread进行锻炼。