【发布时间】:2019-03-09 07:51:16
【问题描述】:
我正在使用带有 Angular 6 的 MEAN Stack 开发一个 Web 应用程序。我的 html 中有一个按钮来获取默认值,当我单击该按钮时,它应该使用默认值填充表单字段。这是我的 html 表单。
<div style="float: right" id="extrudedHeightPanel" *ngIf="isExtrudedHeight" name="extrudedHeight">
<form #extrudedHeightForm="ngForm" (ngSubmit)="saveExtrudedHeightValue(extrudedHeightForm)" #form="ngForm">
<nb-card class="action-buttons">
<div class="form-input-group">
<div class="row">
<div class="">
<button type='button' (click)="setDefaultValues()" class="btn btn-sm btn-rectangle btn-default text-case">Restore Default</button>
</div>
<div class="">
<button type="submit" class="btn btn-sm btn-rectangle btn-default text-case">Done</button>
</div>
</div>
</div>
</nb-card>
<br>
<br>
<br>
<p>Extruded Height</p>
<br>
<div class="form group">
Extruded Height:
<input type="text" nbInput name="extrudedHeight" [(ngModel)]="extrudedHeight" />
</div>
</form>
</div>
我从 mongo db 获取数据到我的 .ts 文件,并尝试使用 Angular 中的“setValue”方法为表单字段设置值。 .ts 文件
class{
extrudedHeightForm: FormGroup;
ngOnInit()
{
this.extrudedHeightForm = new FormGroup({
extrudedHeight: new FormControl()
});
}
//Set default values for extrudedHeight
setDefaultValues() {
this.extrudedHeightService.getExtrudedHeight("default").subscribe(data => {
this.extrudedHeightForm.setValue({
extrudedHeight:data['extrudedHeight']
});
});
}
}
我的问题是以下部分不起作用。我错了还是有什么方法可以满足我的要求。
this.extrudedHeightForm.setValue({
extrudedHeight:data['extrudedHeight']
});
--已更新--
当我变成this.extrudedHeightForm.get('extrudedHeight').setValue(data['extrudedHeight']);
正如答案中所建议的那样,它也不起作用。为了检查值,我打印了一个 console.log。
'console.log(this.extrudedHeightForm.get('extrudedHeight'));'部分给出以下值。
但值 250 未显示在表单字段中。
【问题讨论】:
-
patchValue() 有效吗? angular.io/guide/reactive-forms#patching-the-model-value
-
它不起作用,但它有什么作用?没有? data['extrudedHeight'] 的值是否改变了?订阅块触发了吗?
-
补丁值也不起作用
-
@danday74 data['extrudedHeight'] 的值是相同的。当我尝试调试时,我什至无法为“extrudedHeight:data['extrudedHeight']”行设置断点
-
如果值相同,那么当您设置该值时,什么都不会改变。如果无法设置断点,请使用 console.log。
标签: node.js angular mean-stack