【发布时间】:2019-12-28 17:40:20
【问题描述】:
我有 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
}
}
对于其余的组件,一切都将相同,只是反应式表单和模板本身会有所不同(会有更多或更少的字段)。告诉我在这种情况下如何避免重复?
【问题讨论】:
-
其他组件扩展的抽象 AddAComponent 怎么样?
-
遵循智能组件和哑组件的模式,使用transclusion /slots/
<ng-content>来复用不同子模板的组件。
标签: angular angular6 angular7 angular-components angular8