首页 > 解决方案 > 补丁值角度 6 不起作用

问题描述

当我尝试 patchValue 时,它​​根本不起作用。也没有错误。

@ViewChild('sForm') serviceplanForm: NgForm;

objectid = '';
allisloaded = true;
edit = false;

constructor(private service: GeneralService,
          private route: ActivatedRoute,
          private router: Router) { }

ngOnInit() {

this.objectid = this.route.snapshot.params['id'];

this.route.queryParams.subscribe(params => {

  if (Object.keys(params).length !== 0 && params.constructor === Object) {
    this.edit = true;
    this.allisloaded = true;
    this.setFields(params);
  }
});
}
private setFields(params: any) {
 this.serviceplanForm.form.patchValue({
   objectname: 'asdfsdf'
 });
}

html

<form (ngSubmit)="onSubmit(sForm)" #sForm="ngForm">

    <div class="form-group" [ngClass]="{'has-error': (!objectname.valid && sForm.submitted)}">
      <label>{{ 'serviceplan.NAME' | translate }} <span class="text-danger">*</span></label>
      <input type="text" class="form-control" ngModel #objectname="ngModel" name="objectname" required>
      <span *ngIf="!objectname.valid && sForm.submitted" class="help-block text-danger">{{ 'serviceplane.SERVICEPLANNAMEREQUIRED' | translate }}</span>
    </div>
</form>

相同的代码将在我拥有的其他模块中运行,但由于某种原因它在此组件中不起作用。

当我登录 serviceplanForm 时,表单显示正确。

更新

好的,当我在 httpcall 中调用 patchvalue 时,它​​突然起作用了。但我不想要这个。

this.service.callService(new 
Method(environment.api.methods.objects.getOne  + this.objectid , null, 'get')).subscribe(response => {
  console.log(response);
  this.serviceplanForm.form.patchValue({
      objectname: 'testname'
    });
});

标签: angularformsangular6

解决方案


推荐阅读