在Angular 7中,可以使用表单控件和反应式表单来填充子对象。以下是一个示例代码,演示如何在Angular 7中填充子对象:
ng new angular-form-example
user
的接口,定义一个包含子对象address
的用户对象:export interface User {
name: string;
age: number;
address: Address;
}
export interface Address {
street: string;
city: string;
country: string;
}
app.component.ts
中定义一个名为userForm
的反应式表单,并填充子对象:import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { User } from './user';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
userForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.userForm = this.formBuilder.group({
name: '',
age: '',
address: this.formBuilder.group({
street: '',
city: '',
country: ''
})
});
}
onSubmit() {
const user: User = this.userForm.value;
console.log(user);
}
}
app.component.html
中创建一个表单,用于填充用户和地址信息:
在上述代码中,我们使用formBuilder
创建了一个反应式表单,并使用formControlName
将表单控件与模型对象的属性进行绑定。通过formGroupName
,我们创建了一个子控件组,并将其与子对象的属性进行绑定。
当用户填写表单并提交时,onSubmit
方法将获取表单的值,并将其打印到控制台中。
希望以上解决方法对您有所帮助!