我使用的是反应式表单,我从api提取数据并在输入字段的html中显示,但在控制台中出现了一些错误。需要帮助解决。
以下是HTML代码
<form [formGroup]="homeForm" class="form-horizontal" (ngSubmit)="continue(homeForm.value)">
<div class="form-group">
<label class="control-label" class="text">Officer Name</label>
<input type="text" class="form-control" formControlName="oName" value={{this.home[0].oName}} readonly>
</div>
<div class="form-group">
<label class="control-label" class="text">Officer ID</label>
<input type="text" class="form-control" formControlName="oIDNum" readonly>
</div>
div align="end">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
以下是ts文件代码
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import{Router} from '@angular/router';
import { ApiService } from '../app.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
home:any
constructor(private route:Router,private apiService:ApiService) { }
ngOnInit() {
this.apiService.getData().subscribe((data)=>{
this.home = data;
console.log(this.home);
})
}
homeForm = new FormGroup({
oName:new FormControl(''),
oIDNum:new FormControl(''),
})
continue(value){
console.log(value);
this.route.navigate(['/form']);
}
}
这是服务文件
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private httpClient: HttpClient) { }
public getData(){
return this.httpClient.get(`http://localhost:3000/officer`);
}
}
我正在使用的JSON文件数据如下
{
"officer":[ {
"oName": "Example",
"oIDNum": "1"
}]
}
您可以删除html中的值
value={{this.home[0].oName}}
在TS文件中,您需要像这样写它...
ngOnInit() {
this.apiService.getData().subscribe((data)=>{
this.home = data;
this.homeForm = new FormGroup({
oName:new FormControl(this.home[0].oName),
oIDNum:new FormControl(this.home[0].oIDNum),
})
})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句