0
votes

I am trying to create a reusable input component using angular 9 and material design. Something like the below diagram.

enter image description here

TextboxComponent.html

<mat-form-field appearance="fill">
    <mat-label>Input</mat-label>
    <input matInput formControlName = {{imeta.formControlName}}>
</mat-form-field>

TextboxComponent.ts

@Component({
   selector: 'app-textbox',
   templateUrl: './textbox.component.html',
   styleUrls: ['./textbox.component.scss']
  })
export class TextboxComponent implements OnInit {
  @Input()imeta : IMeta
  constructor() { }
  ngOnInit(): void {}
}

export class IMeta {
    component: ComponentType;
    formControlName : string = null;
}

export enum ComponentType {
    TextBox = 0,
    TextArea = 1,
    RadioButton = 2,
    Checkbox = 3,
    Select = 4
}

This is a configurable component which acts like a bridge.

reactive-base-inputs.component.html

<ng-container [ngSwitch]="imeta.component">
    <ng-template [ngSwitchCase]="componentType.TextBox">
        <app-textbox [imeta]="imeta"></app-textbox>
    </ng-template>
</ng-container>

@Component({
  selector: 'reactive-inputs',
  templateUrl: './reactive-base-inputs.component.html',
  styleUrls: ['./reactive-base-inputs.component.scss']
})
export class ReactiveBaseInputsComponent implements OnInit {
  @Input() imeta : IMeta;
  componentType = ComponentType
  constructor() { }

  ngOnInit(): void {}
}

THis is where I am consuming my input component.

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <reactive-inputs [imeta]="configuration"></reactive-inputs>
</form>

I am facing the issue with the formControlName get and set and I am not getting any idea how I can seta a formControlName and access the control from the parent component.

1

1 Answers

1
votes

I had the same question, while searching I came across 2 articles which helped me a lot. I managed to create reusable Material components.

https://inglkruiz.github.io/angular-material-reusable-autocomplete/

and

https://ritchiejacobs.be/angular-custom-form-component

The important point when creating a reusable component is to access the value of the reusable component from the component where it is used. This can be done via the ControlValueAccessor interface.

Hope this help!