简体   繁体   中英

Reusable input components using Angular 9 and Material design

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

在此处输入图像描述

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM