我有一个组件A,它也具有另一个组件B也需要使用的2个函数和2个类属性的集合。以前我只是将那些代码部分复制粘贴到组件B中并使用它。但是我很确定做一些冗余的代码是不正常的。
编辑:实际上,我具有复杂形式的组件“添加元素”第二个是“修改元素”,我想对这两个组件使用相同的框架。
有人知道在Angular 8中实现此目标的方法吗?预先感谢,
如果目标是避免冗余代码,并且组件不需要共享状态(属性值),则可以使用抽象类。
export abstract class AbstractComponent {
property1: string;
property2: long;
commonMethod(): string {
...
}
}
@Component({
selector: 'app-component1',
...
})
export class Component1 extends AbstractComponent {
...
}
@Component({
selector: 'app-component2',
...
})
export class Component2 extends AbstractComponent {
...
}
我在我的应用中使用了相同的场景。我想创建动态地址组件。用于多种形式。所以首先我创建通用组件
import { Component, OnInit, Input, Output, EventEmitter, OnDestroy, AfterViewInit } from '@angular/core';
import { AddressModal } from '../../modals/opportunity.modal';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-address',
templateUrl: './address.component.html',
styleUrls: ['./address.component.css'],
})
export class AddressComponent implements OnInit, AfterViewInit {
form_address: FormGroup;
@Input('addressModal') addressModal: AddressModal;
@Output()
private formReady: EventEmitter<FormGroup> = new EventEmitter<FormGroup>();
listCountry = [];
public formSubmitAttempt: boolean = false;
constructor(private fb: FormBuilder) {
this.getCountryList();
this.createForm();
}
ngOnInit(): void {
this.formReady.emit(this.form_address);
if (this.addressModal && this.addressModal !== undefined) {
setTimeout(function () {
this.form_address.setValue(this.addressModal);
}.bind(this), 500);
}
}
ngAfterViewInit(): void {
}
createForm() {
const requiredValidations = [
Validators.required,
this.conf.noWhitespaceValidator,
];
this.form_address = this.fb.group({
id: [''],
row_id: [''],
opportunity_id: [''],
address1: ['', requiredValidations],
address2: [''],
city: ['', requiredValidations],
state: ['', requiredValidations],
zipcode: ['', requiredValidations],
country: ['S1ptmVWUWsjyGvlr', requiredValidations],
added_date: [''],
modified_date: [''],
status: ['']
});
}
getCountryList() {
let _self = this;
this.conf.getApiCall('get_countries', {}, function (res) {
if (res.data !== undefined && res.data.countries != undefined) {
_self.listCountry = res.data.countries;
}
}, function (err) {
console.log(err);
});
}
}
然后我在我们的component.html文件中实现
<app-address (formReady)="addFormControl($event)" [addressModal]="address"></app-address>
component.ts文件中的火灾事件发生后
private addFormControl(name: string, formGroup: FormGroup): void {
if (!this.form1.controls[name] && !this.form1.controls[name] !== undefined) {
this.form1.addControl(name, formGroup);
}
}
private addBlankAddress(): void {
let address_obj: AddressModal = {
id: '',
row_id: this.conf.randomRowId(),
opportunity_id: '',
address1: '',
address2: '',
city: '',
state: '',
zipcode: '',
country: 'S1ptmVWUWsjyGvlr',
added_date: '',
modified_date: '',
status: ''
};
this.list_address.push(address_obj);
//return address_obj;
}