在Angular中,使用响应式表单时,如果想要在ngOnInit中加载值并在表单中显示出来,需要使用setValue()或patchValue()方法。这些方法可以将值设置为表单控件中,并将其显示出来。
以下是一个示例代码:
在组件中定义表单:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
firstName: '',
lastName: ''
});
this.myForm.setValue({
firstName: 'John',
lastName: 'Doe'
})
}
}
在模板中显示表单:
在上面的示例中,ngOnInit中的setValue()方法将名字和姓氏的值设置为表单中的控件,并将其显示出来。