FormGroup.patchValue 不会更新空值的文本框视图



我有一个文本框表单控件,我从后端获取值,然后使用补丁值分配给文本框值。如果我在文本框中键入任何内容并单击按钮,那么它会从后端获取空值,但文本框视图没有更新为空值,仍然显示我键入的文本。

剖腹产组件.html

<div [formGroup]="plf.cueForm">
<div class="panel-body">
<div class="row form-group ct-margin-b-20">
<ng-container *ngFor="let ctrl of displayControls;">
<div *ngIf="!plf.state_defn[ctrl.id]" [class]="layoutCls">
<app-c-textbox *ngIf="ctrl.type == 'text' && ctrl.event != '' && ctrl.event != undefined" [formControlName]="ctrl.id" [label]="ctrl.label"
[format]="ctrl.format" (textBoxOnEnter)="plf.handleEvent(ctrl.event)" [mandatory]="ctrl.mandatory"
[InputLength]="ctrl.InputLength" [inputFormat]="ctrl.inputFormat">
</app-c-textbox>
</div>
</div>
/div>

c-sectioncomponent.ts

import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { PlfDataSourceService } from '../../controls/plf-data-source.service'
import { PlfHelpSourceService } from '../../controls/plf-help-source.service'

@Component({
selector: 'app-c-section',
templateUrl: './c-section.component.html',
styleUrls: ['./c-section.component.css']
})
export class CSectionComponent implements OnInit {
@Input() title: String = "";
@Input() controls: any[];
@Input() collapsed: String;
@Input() btnID: String;
@Input() helpFlag: boolean = false;
@Input() hidden: String;
hiddenFlag: String = 'false';
collapseSection: String = 'false';
displayControls: any[];
plf: any;
randomNumber: any;
@Input() columns: any;
constructor(private plfMain: PlfDataSourceService,
private plfHelp: PlfHelpSourceService
) {
}
ngOnInit() {
this.collapseSection ='false';
if (this.hidden != undefined) {
this.hiddenFlag = this.hidden;
}
if (this.collapsed != undefined) {
if (this.collapsed == 'true') 
{
this.collapseSection = 'true';
}
if (this.collapsed == 'false') 
{
this.collapseSection = 'false';
}
}
if (this.helpFlag) {
this.plf = this.plfHelp
}
else {
this.plf = this.plfMain
}
this.randomNumber = this.plfMain.getRandom();
if (this.controls != undefined) {
this.controls.forEach(element => {
this.plf.cueForm.removeControl(element.id);
if (element.mandatory != undefined) {
if (element.type == 'datetime') {
this.plf.cueForm.addControl(element.dateId, new FormControl('', [Validators.required]));
this.plf.cueForm.addControl(element.timeId, new FormControl('', [Validators.required]));
}
else {
this.plf.cueForm.addControl(element.id, new FormControl('', [Validators.required]));
}
}
else {
if (element.type == 'datetime') {
this.plf.cueForm.addControl(element.dateId, new FormControl('', []));
this.plf.cueForm.addControl(element.timeId, new FormControl('', []));
}
else {
this.plf.cueForm.addControl(element.id, new FormControl('', []));
}
}
if (element.type == 'datetime') {
this.plf.controlLabel[element.dateId] = element.label;
this.plf.controlLabel[element.timeId] = element.label;
}
else {
this.plf.controlLabel[element.id] = element.label;
}
});
this.displayControls = this.controls.filter(
(element) => {
if (element.type != "hidden")
return true;
}
)

}
}

}

ctextbox组件.html

<i *ngIf="mandatory" class="mandatory-field">*&nbsp;</i><label>{{label}}</label>
<input type="text" class="form-control ct-input" 
[value]="val"
[attr.maxlength]="InputLength"
(change)="onChange($event.target.value)"
(keydown.enter)="onEnter($event.target.value)"
(keydown)="onkeydown($event,$event.target.value)"
(contextmenu)="onContextmenu($event)"
(blur)="onBlur($event.target.value,$event)"
data-col-index="0"/>    

ctextboxcomponent.ts

import { Component, OnInit, forwardRef,Input, EventEmitter, Output } from '@angular/core';
import { ControlValueAccessor,NG_VALUE_ACCESSOR, } from '@angular/forms';
import { MessageService } from 'primeng/api';
import swal from 'sweetalert2';
import { PlfDataSourceService } from '../../controls/plf-data-source.service'
const CUSTOM_VALUE_ACCESSOR: any = {
provide : NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CTextboxComponent),
multi : true,
};
@Component({
selector: 'app-c-textbox',
templateUrl: './c-textbox.component.html',
styleUrls: ['./c-textbox.component.css'],
providers : [CUSTOM_VALUE_ACCESSOR]
})
export class CTextboxComponent implements OnInit, ControlValueAccessor {
@Input() label:String;
@Input() mandatory:String;
@Input() InputLength:any;
@Input() inputFormat:String;
@Input() format:String;
@Input() precision:any;
@Input() EventFlag:String="N";
@Output() textBoxOnEnter: EventEmitter<any> = new EventEmitter();
val:String;
private disabled: boolean;
private onChange: Function;
private onTouched: Function;
constructor(private messageService: MessageService,private plfMain: PlfDataSourceService) { 
this.onChange = (_: any) => { };
this.onTouched = () => {};  
}
ngOnInit() {
if(this.inputFormat ==undefined) this.inputFormat="string";
}
writeValue(obj: any): void {
this.val = obj;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
onEnter(val)
{
}
onContextmenu(evt)
{
}
onkeydown(event,val)
{    
}
validateNumber(evt) 
{
}
validateNumeric(evt, value) 
{
}
}
onBlur(val,scope)
{
}
validateEmail(field) {
}
validateMultipleEmailsCommaSeparated(value, seperator,scope) {    
}
}

plf.service.ts

import { Injectable, EventEmitter, Output } from '@angular/core';
import { FormBuilder } from '@angular/forms'
import { HttpRequestService } from '../utils/http-request.service';
import { ActivatedRoute, Router } from '@angular/router'
@Injectable({
providedIn: 'root'
})
export class PlfDataSourceService {
cueForm = this.fb.group({});

constructor(private fb: FormBuilder,private httpService: HttpRequestService,private routerLink: Router,) {};
onScreenLoad(activeRoute: ActivatedRoute) 
this.httpService.configRequestDataWithHeaders(requestData, 'post', '').subscribe(
(response) => {
this.cueForm.patchValue(response['hdrcache'][0]);
for (var key in response['hdrcache'][0]) {
if (response['hdrcache'][0][key] == '') {
this.cueForm.patchValue({'strCalendarCodeFrom': response['hdrcache'][0]['strCalendarCodeFrom']});
}
}
);

}

尽管补丁值确实适用于设置表单控件值。如果有帮助,您可以尝试此操作:

this.myForm.controls['name'].setValue('abcd');

你的表单应该是这样的

this.myForm = new FormGroup({
name : new FormControl("")
});

然后你可以像这样设置值

this.myForm.controls['name'].setValue(<your value>);

像这样尝试 this.myForm.patchValue({ 名称:空 });

null值设置为名称属性后,请尝试console.log(this.myForm.value);具有null值的名称属性。但是在将值放入名称输入值后,将替换为您给定的任何输入。

终于我找到了问题的答案..需要订阅值更改方法以使用修补程序值更新视图。

this.cueForm.valueChanges.subscribe(data => {
this.cueForm.patchValue(data, { emitEvent: false });
})

最新更新