NgForm.patchValue在ngOnInIt中不起作用,但在点击处理程序中调用时可以正常工作

时间:2018-08-06 12:56:32

标签: angular

NgForm.patchValuengOnInIt中不起作用,但是在点击处理程序中调用时可以正常工作。我尝试过ngZone或从.patchValue()打电话给ngAfterViewInit,但没有成功。

Stackbliz

html

<form #f="ngForm">
  <input type="text" name="test" ngModel>
</form>

<button (click)="click()">Click me</button>

ts:

 @ViewChild('f') f:NgForm;
  constructor(private zone: NgZone){}

  ngOnInit(){
   this.f.form.patchValue({test:123});
   //this.f.form.updateValueAndValidity();
   // this.zone.run(()=>{
   //   this.f.form.patchValue({test:123});
   // })
  }
  click(){
    this.f.form.patchValue({test:123})
  }

  ngAfterViewInit(): void {
    // this.f.form.patchValue({test:123})
  }

1 个答案:

答案 0 :(得分:0)

Angular FormGroup具有诸如patchValue()之类的方法。

html:

<form [formGroup]="form">

 <input formControlName="first">
 <input formControlName="last">

</form>

在ts中:

const form = new FormGroup({
   first: new FormControl(),
   last: new FormControl()
});
console.log(form.value);   // {first: null, last: null}

form.patchValue({first: 'Nancy'});
console.log(form.value);   // {first: 'Nancy', last: null}