我试图通过表单组使用patchValue()
设置输入值,但输入仍然是空白,这是我的代码示例...
component.html
<form [formGroup]="createStoreForm" (ngSubmit)="createStore()" novalidate>
<label for="user">Unique User ID</label>
<input type="text" name="user" class="form-control" [(ngModel)]="storeProfile.user" [formControl]="createStoreForm.controls['user']" readonly>
<div *ngIf="createStoreForm.controls['user'].hasError('required') && formSubmitAttempt" class="form-error">Store user is required</div>
</form>
component.ts
export class storeProfileComponent implements OnInit {
storeProfile: any = {};
userData: any = {};
userId: any;
createStoreForm: FormGroup;
formSubmitAttempt: boolean;
constructor(fb: FormBuilder, private storeSrv: StoreService, private router: Router) {
this.createStoreForm = fb.group({
'user': ['', Validators.required],
});
}
ngOnInit() {
let tempUser = localStorage.getItem('user');
if (tempUser) {
this.userData = JSON.parse(tempUser);
this.userId = this.userData.id;
};
this.createStoreForm.patchValue({
'user': this.userId.id, // this.userId.id = undefined here
});
}
}
将值从localStorage
传递到表单上的input field
的正确方法是什么?
2 回答
只需删除 ngModel 并使用 createStoreForm.value 来获取值
从这样的本地存储中获取值后需要设置值,
试试这个 -