我有3种类型的对象:
A
- FirstName
- LastName
B
- FirstName
- LastName
- MiddleName
C
- FirstName
我需要创建一个用于创建这些对象的组件,该组件的格式很简单,允许我填写字段并发送请求。
对于每种类型,我创建了一个组件:
a.component.ts:
@Component({
selector: 'add-a-type',
template: `
<form [formGroup]="aForm">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" id="firstName" class="form-control" formControlName="firstName" />
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" class="form-control" formControlName="lastName" />
</div>
<button type="button" class="btn btn-info" (click)="addA()" [disabled]="aForm.invalid">
Add
</button>
</form>
`
})
export class AddAComponent implements OnInit {
aForm: FormGroup;
constructor(
) { }
ngOnInit() {
this.createAForm();
}
createAForm(): void {
this.aForm = new FormGroup({
firstName: new FormControl('', [Validators.required]),
lastName: new FormControl(''),
});
}
addA(): void {
// code
}
}
对于其余组件,一切都将相同,仅反应形式和模板本身将有所不同(会有更多或更少的字段)。告诉我在这种情况下如何避免重复?
答案 0 :(得分:0)
像这样创建一个组件FormComponent:
@Component({
selector: 'app-form',
template: `
<form [formGroup]="form" (submit)="onSubmit()">
<div class="form-group" *ngIf="firstName">
<label for="firstName">First Name</label>
<input
type="text"
id="firstName"
class="form-control"
formControlName="firstName"
/>
</div>
<div class="form-group" *ngIf="middleName">
<label for="middleName">Middle Name</label>
<input
type="text"
id="middleName"
class="form-control"
formControlName="middleName"
/>
</div>
<div class="form-group" *ngIf="lastName">
<label for="lastName">Last Name</label>
<input
type="text"
id="lastName"
class="form-control"
formControlName="lastName"
/>
</div>
<button
type="button"
class="btn btn-info"
(click)="submitBtn()"
[disabled]="form.invalid"
>
Add
</button>
</form>
`
})
export class FormComponent implements OnInit {
@Input() firstName: boolean;
@Input() middleName: boolean;
@Input() lastName: boolean;
@Output() formSubmit = new EventEmitter<any>();
public form: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
firstName: this.firstName ? new FormControl('', [Validators.required]) : undefined,
middleName: this.middleName ? new FormControl('', [Validators.required]) : undefined,
lastName: this.lastName ? new FormControl('', [Validators.required]) : undefined
});
}
onSubmit() {
if(this.form.valid) {
this.formSubmit.emit(this.form.value);
}
}
}
然后在您的页面上使用它。例如,如果您只想要名字和姓氏:
<app-form (formSubmit)="onSubmit($event)" [firstName]="true" [lastName]="true"></app-form>