FormControlName在Angular 7材料模式中不显示以前的值可能是由于以下原因导致的:
对于上述问题,以下是一些可能的解决方法:
// 组件类
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
exampleForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.exampleForm = this.fb.group({
name: ['', Validators.required],
email: ['', Validators.email],
// 其他表单控件
});
}
}
// 组件类
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
exampleForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
const initialValue = {
name: 'John',
email: 'john@example.com',
// 其他表单控件的初始值
};
this.exampleForm = this.fb.group({
name: [initialValue.name, Validators.required],
email: [initialValue.email, Validators.email],
// 其他表单控件
});
}
}
// 组件类
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
exampleForm: FormGroup;
initialValue = {
name: 'John',
email: 'john@example.com',
// 其他表单控件的初始值
};
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.exampleForm = this.fb.group({
name: [this.initialValue.name, Validators.required],
email: [this.initialValue.email, Validators.email],
// 其他表单控件
});
}
resetForm() {
this.exampleForm.reset(this.initialValue); // 重置表单为初始值
}
}
// 组件类
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
exampleForm: FormGroup;
initialValue = {
name: '',
email: '',
// 其他表单控件的初始值
};
constructor(private fb: FormBuilder, private http: HttpClient) { }
ngOnInit() {
this.http.get('api/data').subscribe((data: any) => {
this.initialValue = data; // 从服务器获取数据
this.initForm();
}, error => {
console.error('Failed to fetch data:', error);
this.initForm();
});
}
initForm() {
this.exampleForm = this.fb.group({
name: [this.initialValue.name, Validators.required],
email: [this.initialValue.email, Validators.email],
// 其他表单控件
});
}
}
确保在组件的模板中正确绑定FormControlName:
<!-- 组件模板 -->
<form [formGroup]="exampleForm">
<input type="text" formControlName="name">
<input type="email" formControlName="email">
<!-- 其他表单控件 -->
</form>
以上是一些可能导致FormControlName在Angular 7材料模式中不显示以前的值的原因和解决方法。希望对你有帮助!
领取专属 10元无门槛券
手把手带您无忧上云