初始化 FormGroup
时并禁用 FormGroup
或 FormControl
在 HttpClient.get
回调,FormGroup
在 HTML 中未禁用,但 disabled
属性(property)报告为 true
.
请参见工作示例 here
我可以通过将禁用的代码包装在如下超时中来解决这个问题,但这不是可取的:
setTimeout(() => {
this.form.disable();
});
不设置
FormGroup
时它确实有效到一个新实例,但我想将它设置为一个新实例。重现问题的最小示例:
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { PersonService } from './person.service';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'my-app',
template: `
<form [formGroup]="form">
<button class="btn btn-primary" (click)="onFetchPerson()">Click Me</button>
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" formControlName="firstName" />
</div>
<div class="form-group">
<label>Surname</label>
<input type="text" class="form-control" formControlName="surname" />
</div>
<div class="form-group">
Disabled:{{form.disabled}}<br>
Status:{{form.status}}
</div>
</form>
`,
})
export class App implements OnInit {
public form: FormGroup;
constructor(private personService: PersonService) {}
ngOnInit(): void {
this.form = new FormGroup({
firstName: new FormControl(),
surname: new FormControl(),
});
}
public onFetchPerson() {
this.personService.fetchPerson().subscribe(() => {
this.form = new FormGroup({
firstName: new FormControl('John'),
surname: new FormControl('Doe'),
});
this.form.disable();
console.log(this.form);
});
}
}
@Injectable({
providedIn: 'root',
})
export class PersonService {
constructor(private http: HttpClient) {}
public fetchPerson = () => this.http.get('https://randomuser.me/api');
}
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule],
declarations: [App],
bootstrap: [App],
providers: [
PersonService
]
})
export class AppModule {}
最佳答案
您可以使用 ChangeDetectorRef
对于你的问题
这是一个例子
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
export class App implements OnInit {
constructor(private personService: PersonService, readonly cd: ChangeDetectorRef) {}
public onFetchPerson() {
this.personService.fetchPerson().subscribe(() => {
this.form = new FormGroup({
firstName: new FormControl('John'),
surname: new FormControl('Doe'),
});
this.cd.detectChanges();
this.form.disable();
console.log(this.form);
});
}
}
关于angular - 禁用 FormGroup 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52219880/