0

I have a Component A which has a set of 2 functions and 2 class attributes that another component B needs to use too. Previously I just copy paste those code parts into the component B and use it. But I'm pretty sure it's not normal to do some redundant code.

EDIT: In fact I have a component "add element" with complex forms and a second one "modify element" and I want to use the same skeleton for those two components.

Is someone know a way to achieve this in Angular 8? Thanks in advance.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

2 Answers2

0

If the goal is avoiding redundant code and the components don't need to share state (property values), you can use an abstract class.

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 {
   ...
}
uminder
  • 23,831
  • 5
  • 37
  • 72
0

i used same scenario my application. i want to create dynamic address component. for used many forms. so first i create common component

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);
    });
  } 
}

then i implement in our component.html file

   <app-address (formReady)="addFormControl($event)" [addressModal]="address"></app-address>

after fire event in component.ts file

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;
}
Arvind
  • 74
  • 14
  • Hi, i want to share and use the same form in 2 components. One component is for inserting and the second one is to modify so it has some values preselected in the form. How can i handle this ? i tried to make a service but when i create form in the service and patchValue on the form inside the component, it says patchValue is nocannot read patchValue of undefined. And when i tired top console log the form its ok the form is delcared and initialized. – Guillaume OSTORERO Oct 31 '19 at 09:44