我有这个自动完成的内部表格
<input type="text" placeholder="Pilih Bank" matInput [matAutocomplete]="auto" formControlName="bankName">
<mat-autocomplete #auto="matAutocomplete" (optionSelected)='onChangeBank()' [displayWith]="displayFn">
<mat-option>Pilih Bank</mat-option>
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option.bankName}}
</mat-option>
</mat-autocomplete>
当我尝试使用initForm()
并且用户具有bankName的值时,我想用用户值填充formControlName
,但是无论如何它都不会改变。
这是在我的`TS
中// Angular
import { Component, EventEmitter, OnInit, Output, ViewChild, OnDestroy } from '@angular/core';
import { ViewportScroller } from '@angular/common';
import { AbstractControl, FormBuilder, FormGroup, NgForm, Validators, FormControl } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
// Extension
import { Subject, Subscription, Observable } from 'rxjs';
import {map, startWith} from 'rxjs/operators';
import { distinctUntilChanged, takeUntil } from 'rxjs/operators';
import * as _ from 'lodash';
import { ValidationsService } from '../../../shared/validations.service';
import { BankService } from '../../../shared/bank.service';
export interface User {
bankCode: string;
bankName: string;
}
@Component({
selector : 'fp-kyc-legal-data-form',
templateUrl: './fp-legal-data-form.view.html',
styleUrls : ['../fp-kyc.style.scss']
})
export class FpLegalDataFormComponent implements OnInit, OnDestroy {
form: FormGroup;
tmpIdentityImg: string;
tmpPaySlipImg: string;
tmpTaxImg: string;
tmpDocument: string;
isSubmitted: boolean;
kliringCode= new Subject<string>();
getBankAccountSub : Subscription;
kliringCodeSub : Subscription;
convertBankCodeSub : Subscription;
interval;
timeLeft: number;
myControl = new FormControl();
options: User[];
filteredOptions: Observable<User[]>;
public profileData;
private limitSizeUpload = 5242880;
private unSubs$: Subject<any> = new Subject<any>();
@Output('legalDataStatus') legalDataStatus: EventEmitter<boolean> = new EventEmitter<boolean>();
@ViewChild('legalDataFrm') legalDataFrm: NgForm;
constructor(
private activatedRoute: ActivatedRoute,
private formBuilder: FormBuilder,
public _validationsService: ValidationsService,
private $viewportScroller: ViewportScroller,
public _bankService: BankService
) {
this.$viewportScroller.scrollToPosition([0, 0]);
this.profileData = this.activatedRoute.snapshot.data.profile;
this.tmpIdentityImg = '';
this.tmpPaySlipImg = '';
this.tmpTaxImg = '';
this.tmpDocument = '';
this.isSubmitted = false;
}
ngOnInit() {
this.initForm();
this.initDropdown();
this.form.statusChanges
.pipe(
takeUntil(this.unSubs$),
distinctUntilChanged()
)
.subscribe((status: string) => {
this.legalDataStatus.emit(status === 'INVALID');
});
}
displayFn(user?: User): string | undefined {
console.log(user)
return user ? user.bankName : '';
}
private _filter(name: string): User[] {
const filterValue = name.toLowerCase();
return this.options.filter(option => option.bankName.toLowerCase().indexOf(filterValue) > -1);
}
ngOnDestroy() {
if(this.kliringCodeSub) this.kliringCodeSub.unsubscribe();
if(this.getBankAccountSub) this.getBankAccountSub.unsubscribe();
if(this.convertBankCodeSub) this.convertBankCodeSub.unsubscribe();
}
onSubmit() {
this.isSubmitted = true;
this.legalDataFrm.ngSubmit.emit();
for (const fieldName in this.fControls) {
if (this.fControls.hasOwnProperty(fieldName)) {
this.form.get(fieldName).markAsTouched();
this.form.get(fieldName).updateValueAndValidity();
}
}
}
onCheckIdentityImg(ev: Event) {
const inputEl = (ev.target as HTMLInputElement);
if (inputEl.files && inputEl.files.length > 0) {
const file = inputEl.files[0];
this.form.patchValue({ identityImg: file });
this.form.get('identityImg').markAsTouched();
const reader = new FileReader();
reader.onload = () => {
this.form.patchValue({ identityImgURL: reader.result });
this.form.get('identityImgURL').updateValueAndValidity();
this.tmpIdentityImg = file.name;
};
reader.readAsDataURL(file);
}
}
onCheckPaySlipImg(ev: Event) {
const inputEl = (ev.target as HTMLInputElement);
if (inputEl.files && inputEl.files.length > 0) {
const file = inputEl.files[0];
this.form.patchValue({ paySlipImg: file });
this.form.get('paySlipImg').markAsTouched();
const reader = new FileReader();
reader.onload = () => {
this.form.patchValue({ paySlipImgURL: reader.result });
this.form.get('paySlipImgURL').updateValueAndValidity();
this.tmpPaySlipImg = file.name;
};
reader.readAsDataURL(file);
}
}
onCheckTaxImg(ev: Event) {
const inputEl = (ev.target as HTMLInputElement);
if (inputEl.files && inputEl.files.length > 0) {
const file = inputEl.files[0];
this.form.patchValue({ taxImg: file });
this.form.get('taxImg').markAsTouched();
const reader = new FileReader();
reader.onload = () => {
this.form.patchValue({ taxImgURL: reader.result });
this.form.get('taxImgURL').updateValueAndValidity();
this.tmpTaxImg = file.name;
};
reader.readAsDataURL(file);
}
}
onClear(input: AbstractControl | null, label: string, ev: Event) {
switch (label) {
case 'identityImg':
this.tmpIdentityImg = '';
break;
case 'taxImg':
this.tmpTaxImg = '';
break;
case 'paySlipImg':
this.tmpPaySlipImg = '';
break;
case 'document':
this.tmpDocument = '';
break;
}
input.reset();
}
onKeyDown(bankInfo, noRek) {
clearInterval(this.interval);
this.timeLeft = 1;
this.interval = setInterval(() => {
if (this.timeLeft > 0) {
this.timeLeft--;
} else {
clearInterval(this.interval);
const noRekTemp = noRek.target.value;
if (noRekTemp && bankInfo) {
this.convertBankCodeSub = this._bankService.getBankIdByCode(bankInfo.interbankCode, noRekTemp).subscribe((kcVal) => {
this.form.patchValue({ 'bankAccount': kcVal.data.accountName });
});
this.kliringCodeSub = this.kliringCode.pipe(distinctUntilChanged()).subscribe((val) => {
if (val) {
this.getBankAccountSub = this._bankService.getBankAccountName(val, noRekTemp).subscribe((res) => {
if (res.status === 'success') {
this.form.patchValue({ 'bankAccount': res.data.bankAccountName });
this.form.get('bankAccount').markAsTouched();
this.form.get('bankAccount').updateValueAndValidity();
}
});
}
});
}
return;
}
}, 500);
}
onChangeBank() {
this.form.patchValue({ 'rekNo': '' });
this.form.get('rekNo').markAsTouched();
this.form.get('rekNo').updateValueAndValidity();
this.form.patchValue({ 'bankAccount': '' });
this.form.get('bankAccount').markAsTouched();
this.form.get('bankAccount').updateValueAndValidity();
};
get fControls() {
return this.form.controls;
}
private initDropdown() {
this._bankService.getBank2().then((response) => {
this.options = response;
this.filteredOptions = this.form.controls.bankName.valueChanges
.pipe(
startWith<string | User>(''),
map(value => typeof value === 'string' ? value : value.bankName),
map(name => name ? this._filter(name) : this.options.slice())
);
})
}
private initForm() {
let bankName = null;
let rekNo = null;
let bankAccount = null;
const identityImg = null;
const taxImg = null;
const paySlipImg = null;
const identityImgURL = null;
const taxImgURL = null;
const paySlipImgURL = null;
const legalData = JSON.parse(localStorage.getItem('legalData'));
if (legalData) {
if (
_.hasIn(this.profileData, 'borrower.bankAccount.bankName') &&
!legalData.bankName &&
_.hasIn(this.profileData, 'borrower.bankAccount.bankCode')
) {
if (this.profileData.borrower.bankAccount.bankCode) {
bankName = legalData.bankName
}
} else {
// bankName = legalData.bankName;
bankName = this.form.get('bankName').value;
}
if (
_.hasIn(this.profileData, 'borrower.bankAccount.bankAccountNo') &&
!legalData.rekNo
) {
rekNo = this.profileData.borrower.bankAccount.bankAccountNo;
} else {
rekNo = legalData.rekNo;
}
if (
_.hasIn(this.profileData, 'borrower.bankAccount.bankAccountName') &&
!legalData.bankAccount
) {
bankAccount = this.profileData.borrower.bankAccount.bankAccountName;
} else {
bankAccount = legalData.bankAccount;
}
setTimeout(() => {
for (const fieldName in this.form.controls) {
if (this.form.controls.hasOwnProperty(fieldName)) {
if (this.form.get(fieldName).value) {
this.form.get(fieldName).markAsTouched();
this.form.get(fieldName).updateValueAndValidity();
}
}
}
});
} else {
if (
_.hasIn(this.profileData, 'borrower.bankAccount.bankName') &&
_.hasIn(this.profileData, 'borrower.bankAccount.bankCode')
)
{
bankName = this.profileData.borrower.bankAccount.bankName
}
if (_.hasIn(this.profileData, 'borrower.bankAccount.bankAccountNo')) {
rekNo = this.profileData.borrower.bankAccount.bankAccountNo;
}
if (_.hasIn(this.profileData, 'borrower.bankAccount.bankAccountName')) {
bankAccount = this.profileData.borrower.bankAccount.bankAccountName;
}
setTimeout(() => {
for (const fieldName in this.form.controls) {
if (this.form.controls.hasOwnProperty(fieldName)) {
if (this.form.get(fieldName).value) {
this.form.get(fieldName).markAsTouched();
this.form.get(fieldName).updateValueAndValidity();
}
}
}
});
}
/*const legalData = JSON.parse(localStorage.getItem('legalData'));
if (legalData) {
const file = new File([], legalData.tmpIdentityImg.name, {
type : legalData.tmpIdentityImg.type,
lastModified: legalData.tmpIdentityImg.lastModified
});
identityImg = file;
identityImgURL = legalData.identityImgURL;
taxImgURL = legalData.taxImgURL;
this.tmpIdentityImg = legalData.tmpIdentityImg.name;
this.tmpTaxImg = legalData.tmpIdentityImg.name;
}*/
this.form = this.formBuilder.group({
bankName : [bankName, Validators.required],
rekNo : [rekNo, [Validators.required, Validators.maxLength(20)]],
bankAccount : [bankAccount, Validators.required],
identityImg : [identityImg, Validators.required],
taxImg : taxImg,
paySlipImg : paySlipImg,
identityImgURL: identityImgURL,
taxImgURL : taxImgURL,
paySlipImgURL : paySlipImgURL,
});
this.form.get('bankName').updateValueAndValidity();
if (_.hasIn(this.profileData, 'borrower.account.identityImage')) {
if (this.profileData.borrower.account.identityImage) {
this.form.get('identityImg').clearValidators();
this.form.get('identityImg').updateValueAndValidity();
} else {
this.form.get('identityImg').setValidators([Validators.required]);
this.form.get('identityImg').updateValueAndValidity();
}
}
this._validationsService.numberFormat(this.form.get('rekNo'));
this._validationsService.mimeType(this.form.get('identityImg'));
this._validationsService.sizeLimit(this.form.get('identityImg'), this.limitSizeUpload);
this._validationsService.mimeType(this.form.get('taxImg'));
this._validationsService.sizeLimit(this.form.get('taxImg'), this.limitSizeUpload);
this._validationsService.mimeType(this.form.get('paySlipImg'));
this._validationsService.sizeLimit(this.form.get('paySlipImg'), this.limitSizeUpload);
this.limitSizeUpload);
}
}
答案 0 :(得分:0)
您可以使用patchValue
或setValue
从TS
设置表单值
TS
if (_.hasIn(this.profileData, 'borrower.bankAccount.bankName')) {
//By SetValue
this.form.controls['bankName'].setValue(this.profileData.borrower.bankAccount.bankName);
//By PatchValue
this.form.controls['bankName'].patchValue(this.profileData.borrower.bankAccount.bankName);}
我只是查看您的整个代码,然后再初始化表格
first initialize the form
this.form = this.formBuilder.group({
bankName : [bankName, Validators.required],
rekNo : [rekNo, [Validators.required, Validators.maxLength(20)]],
bankAccount : [bankAccount, Validators.required],
identityImg : [identityImg, Validators.required],
taxImg : taxImg, paySlipImg : paySlipImg,
identityImgURL: identityImgURL,
taxImgURL : taxImgURL,
paySlipImgURL : paySlipImgURL
});
// then set the value
this.form.controls['bankName'].setValue(this.profileData.borrower.bankAccount.bankName);
答案 1 :(得分:0)
所以,我保证如果我发现问题,我会更新此线程,这是我的问题。 抱歉,无法及时更新。 我在initForm()中获得的数据类型是字符串,而当我从选项中选择时发送的数据是对象。所以我需要给一些条件。
displayFn(user?: User) {
if ((typeof user) === 'string') {
return user
}
return user ? user.bankName : '';
}