生成的addText函数在角度中作为null传递



我有一个输入字段,它从onClick事件中获得一个自动生成的字符串,但当我提交发布请求时,它显示为null。当我手动键入一个字符串时,它会接收该值并完美地发布它。

这是我的组件.html

<form [formGroup]="form" (ngSubmit)="submitForm()">
<div class="mat-form-field">
<input class="form-control" placeholder="Name" formControlName="name"
[ngClass]="{ 'is-invalid': submitted && f.name.errors }" style="margin-bottom: 4px">
<input class="form-control" placeholder="City" formControlName="city"
[ngClass]="{ 'is-invalid': submitted && f.city.errors }" style="margin-bottom: 4px">
<div class="flex">
<input #input class="form-control" placeholder="ReferenceNumber" formControlName="referenceNumber" disabled>
<mat-icon (click)="addText()" style="cursor: pointer">autorenew</mat-icon>
</div>
</div>
<div class="modal-footer">
<button mat-raised-button id="modal-action-button">Add Supplier</button>
<button mat-raised-button id="modal-cancel-button" (click)="closeModal()">Cancel</button>
</div>

和我的组件.ts:

addText(){
this.input.nativeElement.focus();
const startPos = this.input.nativeElement.selectionStart;
const value = this.input.nativeElement.value;
this.genCode = Math.random().toString(36).substring(2, 6).toUpperCase() + Math.random().toString(36).substring(2, 6).toUpperCase();
this.input.nativeElement.focus();
this.input.nativeElement.value= this.genCode;
}
submitForm() {
this.submitted = true;
if (this.form.invalid) { return }
const formData: any = new FormData();
formData.append("name", this.form.get('name').value);
formData.append("city",this.form.get('city').value);
formData.append("referenceNumber",this.form.get('referenceNumber').value);
this._Supplier.AddSupplier(new Suppliers(this.form))
.subscribe( response => console.log(JSON.stringify(response)));
if (this.submitted == true){
this.dialogRef.close();
}
this.onSubmitted.emit('done');
}

您只需要设置这样的表单值:

addText() {
const randomText = Math.random().toString(36).substring(2, 6).toUpperCase() + Math.random().toString(36).substring(2, 6).toUpperCase();
this.form.patchValue({
referenceNumber: randomText
});
}

您应该将ur表单组设置为构造函数,并添加set this以引用程序中的所有表单生成器。

我在stackblitz制作并从你的代码编辑

你能试试这个吗。参考角度-表格

最新更新