我正在尝试将检索到的数据分配给表单。数据已正确检索,但是当我尝试将数据的每个值传递到其相应的输入或选择时,它没有正确放置它们。有趣的是,当我在输入之前显示每个值时,该值显示正确。 这是我的班级对象:
export class ConfigGeneral {
idConfigGeneral?: number;
libelleInterneCabinet?: string;
devise?: string;
}
这是打字稿组件
import { Component, OnInit } from '@angular/core';
import { NgbModal} from '@ng-bootstrap/ng-bootstrap';
import { ConfigGeneral } from 'src/app/models/cabinet/configCabinet/ConfigGeneral';
import {ConfigGeneralService} from '../../../Services/cabinet/configuration/config-general.service';
import { map, tap } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-parametre-general',
templateUrl: './parametre-general.component.html',
styleUrls: ['./parametre-general.component.scss']
})
export class ParametreGeneralComponent implements OnInit {
configGeneral : ConfigGeneral
constructor(private modalService: NgbModal,
private configGeneralService:ConfigGeneralService) {
this.configGeneral = new ConfigGeneral()
}
ngOnInit(): void {
this.getConfigurationGeneral()
}
getConfigurationGeneral(){
this.configGeneralService.getConfigGeneralOfCabinet().pipe
(tap((data)=>{
if (data != null){
console.log(data)
this.configGeneral=data;
console.log(this.configGeneral)
}
})
).subscribe();
}
}
这是 html 组件的形式(我将只关注两个值“libelleInterneCabinet”和“devise”以使其清晰易读)
<form >
<div class="form-group row">
<label class="col-sm-4 col-form-label" for="libelleInterne">Libelle interne du cabinet</label>
<div class="col-sm-7">
{{configGeneral.libelleInterneCabinet}}
<input class="form-control" id="libelleInterne" type="text" [(ngModel)]="configGeneral.libelleInterneCabinet">
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label" for="devise">Devise</label>
<div class="col-sm-7">
{{configGeneral.devise}}
<select class="form-select" id="devise" [(ngModel)]="this.configGeneral.devise">
<option value="Euro">Euro</option>
</select>
</div>
</div>
</form>
这是
getConfigurationGeneral()
方法中两个 console.log 的结果:
devise: "Euro"
libelleInterneCabinet: "cabinet"
图中是这样显示的
实际上,我还没有尝试过任何东西,因为我无法识别代码中的问题。我希望我能找到答案。谢谢您的宝贵时间。
我将您的代码粘贴到this StackBlitz并看到以下错误:
错误:NG01352:如果在表单标签中使用 ngModel,则必须设置 name 属性或表单 控件必须在 ngModelOptions 中定义为“独立”。
您是否看到此错误?
只需使用
name
属性而不是 id
属性即可解决问题:
<input type="text" name="libelleInterne" [(ngModel)]="configGeneral.libelleInterneCabinet" />
这是更新后的 StackBlitz