Angular patchValue未设置输入字段值

时间:2018-05-21 11:10:35

标签: angular typescript angular5 formbuilder

我正在尝试使用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 个答案:

答案 0 :(得分:1)

您需要在从本地存储中获取值后设置值,

试试这个 -

onDataChange()

答案 1 :(得分:1)

只需删除ngModel并使用createStoreForm.value从值

获取
<form [formGroup]="createStoreForm" (ngSubmit)="createStore()" novalidate>
  <label for="user">Unique User ID</label>
    <input type="text" name="user" class="form-control" [formControl]="createStoreForm.controls['user']" readonly>
    <div *ngIf="createStoreForm.controls['user'].hasError('required') && formSubmitAttempt" class="form-error">Store user is required</div>
</form>

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,  
  });
 }

 public createStore(){
  console.log(this.createStoreForm.value); // get from values 
 }
}