我正在创建带有输入字段的表单。有一些来自REST API的默认输入字段值。
这是我的模板:
.alertCustomCss{
background-color: red;
color: white;
button{
color: green!important;
}
.alert-wrapper{
background: yellow;
}
.alert-message {
color: skyblue;
}
.alert-title{
color: black;
}
}
还有我的TS代码:
<form [formGroup]="form" (ngSubmit)="action()">
<input type="text" formControlName="name" [value]="fromApi(name)">
</form>
客户端从API获得了默认值。他可以在输入字段中更改该数据。
有两种可能性:
1)他确实更改了来自API的初始值。在那个cas中,当我console.log FormGroup时,我得到了他输入的新值,太完美了!
2)他不想从API更改值。这就是我的问题:在这种情况下,输入名称的值是”(来自FormControl的值)。我想从API中获取值。
有可能吗?谢谢
答案 0 :(得分:1)
确定是。
触发您的方法以从组件ngOnInit
挂钩中的api中获取数据,并在FormControl的patchValue
中取回数据后()。
答案 1 :(得分:0)
您可以尝试以下方法:
ngOnInit(){
this.form = new FormGroup({name:new FormControl('')});
this.fromApi();
}
fromApi(){
//inside the subscribe method of the api called
let valueFromAPI = 'Example';
this.form.controls.name.setValue(valueFromAPI);
}
或
this.fromApi('name');
fromApi(control){
//inside the subscribe method of the api called
let valueFromAPI = 'Example';
this.form.controls[control].setValue(valueFromAPI);
}