使用 Angular 11 的反应形式的动态值 return null
Dynamic value return null in reactive form using Angular 11
我在 angular 中创建了响应式表单,从后端获取了几个字段并应用于输入类型隐藏字段,其值不会改变。我需要将值插入数据库。但是控制台中的值 return null 但在开发人员工具中它显示正确的值。请找到下面的代码
在discussion.component.html文件中
<form [formGroup]="pollResult">
<input type="hidden" value="{{pollQuestion?.id}}" formControlName="pollQuestionId">
<input type="hidden" name="userId" value="1" formControlName="userId">
<div class="radio-group">
<label class="container" *ngFor="let item of pollQuestion?.CM_Poll_Options;let i=index"
> {{item.pollOption}}
<input type="radio" checked="checked" name="pollOption" value="{{item.id}}" formControlName="pollOption"/>
<span class="checkmark"></span>
<small>60%</small>
<div style="width: 60%"></div>
</label>
</div>
<button type="submit" class="submit_vote" (click)="submitPoll(pollResult.value)">
Submit your vote
</button>
</form>
在 discussions.component.ts 文件中
this.pollResult = this.fb.group({
pollQuestionId:[''],
userId:[''],
pollOption:['']
});
在上面的代码中 pollOption 值工作正常,pollQuestionId 和 userId returns null 而不是 return 值属性中应用的值。
删除值 属性
的绑定
<input type="hidden" formControlName="pollQuestionId">
<input type="hidden" name="userId" formControlName="userId">
在你的TS中,设置这个控件的值
ngOnInit() {
this.myService.getData().subscribe({
next: (pollQuestion) => {
this.pollResult.get('pollQuestionId').setValue(pollQuestion?.id);
this.pollResult.get('userId').setValue(1)
}
})
}
我在 angular 中创建了响应式表单,从后端获取了几个字段并应用于输入类型隐藏字段,其值不会改变。我需要将值插入数据库。但是控制台中的值 return null 但在开发人员工具中它显示正确的值。请找到下面的代码
在discussion.component.html文件中
<form [formGroup]="pollResult">
<input type="hidden" value="{{pollQuestion?.id}}" formControlName="pollQuestionId">
<input type="hidden" name="userId" value="1" formControlName="userId">
<div class="radio-group">
<label class="container" *ngFor="let item of pollQuestion?.CM_Poll_Options;let i=index"
> {{item.pollOption}}
<input type="radio" checked="checked" name="pollOption" value="{{item.id}}" formControlName="pollOption"/>
<span class="checkmark"></span>
<small>60%</small>
<div style="width: 60%"></div>
</label>
</div>
<button type="submit" class="submit_vote" (click)="submitPoll(pollResult.value)">
Submit your vote
</button>
</form>
在 discussions.component.ts 文件中
this.pollResult = this.fb.group({
pollQuestionId:[''],
userId:[''],
pollOption:['']
});
在上面的代码中 pollOption 值工作正常,pollQuestionId 和 userId returns null 而不是 return 值属性中应用的值。
删除值 属性
的绑定 <input type="hidden" formControlName="pollQuestionId">
<input type="hidden" name="userId" formControlName="userId">
在你的TS中,设置这个控件的值
ngOnInit() {
this.myService.getData().subscribe({
next: (pollQuestion) => {
this.pollResult.get('pollQuestionId').setValue(pollQuestion?.id);
this.pollResult.get('userId').setValue(1)
}
})
}