Create a set of versatile input elements with Angular 9 and Material design for reus

Currently, I am in the process of developing a reusable input component using Angular 9 along with material design. My goal is to create something similar to the illustration provided below.

https://i.sstatic.net/N1tCy.png

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 component is designed to be configurable and serves as a bridge between different elements.

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 have implemented my input component.

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

I am currently experiencing difficulties with setting and accessing the formControlName. Any suggestions on how I can effectively set a formControlName and access the parent component?

Answer №1

While I was looking for solutions to a similar question, I stumbled upon two helpful articles that guided me in creating reusable Material components.

Check out this link for more information

and

This article also provided valuable insights

Key advice when designing a reusable component is to be able to access its value from the component where it is being utilized. The ControlValueAccessor interface can assist with this task.

I hope you find this information useful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Immutable.Map<K, T> used as Object in Typescript

While refactoring some TypeScript code, I encountered an issue that has me feeling a bit stuck. I'm curious about how the "as" keyword converts a Map<number, Trip> into a "Trip" object in the code snippet below. If it's not doing that, the ...

Whenever I attempt to run the NPM install command in the Terminal, it seems to generate multiple errors

I am encountering an issue on my work laptop. I have the latest versions of Angular, Nodejs, Nodesass, and VScode installed in the local environment path. Whenever I download an Angular template from Github and try to do NPM Install, it consistently thro ...

Publish the file on Angular 7 route for accessibility

I'm currently stuck on an issue that I can't seem to figure out. I'm attempting to link my website to Apple Pay through Stripe's PaymentRequest feature. However, I'm running into difficulties with one of the requirements they have ...

Using TypeScript in combination with Angular for implementing CORS protocol

As I try to send a request to my REST endpoint, the following code is executed: this.http.request(path, requestOptions); The path is set to: http://localhost:8082/commty/cmng/users and the requestOptions are as follows: { headers: { user: "sdf", pas ...

Input field for postal code containing only numbers (maximum 5 digits) in Angular version 4/5

I am struggling with creating an input field that accepts numbers. If I use type="text", I can only type 5 characters of alphanumeric data, but if I use type="number", it allows any number input without limiting it to just 5 numbers. Thank you in advance f ...

Error: The lockfile and package.json file are not synchronized when running npm

Having a problem with NPM where the package-lock and package.json files are out of sync. Tried deleting node_modules, running npm install, but issue persists. Any suggestions? Error: npm ci can only install packages when package.json and package-lock.json ...

Utilizing RxJS to effectively cancel outdated HTTP requests within an Angular service

While I know there are many similar questions out there, I often find them confusing or hard to apply to my specific situation. That's why I'm reaching out here to try and wrap my head around it. In the typescript file of my component, I have a m ...

Tips for preventing chunk loading in webpack: [Angular] [inline js]

Currently, I am working on bundling an Angular project into a single file that includes JS, CSS, and HTML. So far, I've successfully integrated the HTML and CSS, and have made the JS inline using HtmlWebpackInlineSourcePlugin. The minified JS files ge ...

What is the reason for allowing var to declare duplicates, while const and let restrict duplicate declarations?

What is the reason behind var allowing duplicate declaration while const and let do not? var allows for duplicate declarations: xx=1; xx=2; console.log(xx+xx);//4 var xx=1; var xx=2; console.log(xx+xx);//4 However, let and const do not allow for dupl ...

Angular: cut down lengthy text with an ellipsis and display more upon click

I am currently working with Angular 8, Angular Material, and Bootstrap utilities. Below is the code snippet I have been using: <div class="p-1 text-break" *ngSwitchDefault [innerHTML]="cell.value | longText"& ...

Changing the format of a numerical value to include commas for every 1000 increment

I'm trying to find a way to format numbers in a specific manner, such as changing 1234567 into 1,234,567. However, I've run into some issues when attempting to use the currency pipe of TypeScript. It adds USD or $ in front of the number, which i ...

What is the process for creating a default button in Ionic framework?

Recently, I developed an app that includes a survey page. Each question in the survey has two buttons for the user to select: Yes or No. However, as a newcomer to using Ionic, I encountered an issue after building the code and checking the output. One of ...

Creating a new item in Angular 2 using user input

Just dipping my toes into Angular2 and attempting to append a new item to the list through input. However, upon clicking submit, instead of text I get [object Object]. Check out the code snippet below: app.component.html <form (submit)="addItem(item) ...

Controlling the DOM with Angular 2

I am currently developing a website in Angular 2. I have successfully implemented a JQuery code that adds 2 input fields and 1 delete button when a custom button is clicked. When the user clicks on the delete button, it removes the inputs by manipulating t ...

Make sure a Typescript array contains a particular value

Currently, I am in the process of developing a dropdown-style component where the value and options are separate props. My goal is to incorporate Typescript to ensure that the value remains a valid option. Although I could perform this validation at runtim ...

Tips for adding line breaks in TypeScript

I'm brand new to angular and I've been working on a random quote generator. After following a tutorial, everything seemed to be going smoothly until I wanted to add a line break between the quote and the author. Here's what I currently have ...

Aframe's a-assets feature experiencing issues when loading dynamic data through Angular 2

Since there is no fixed number of assets that need to be loaded from the server, I am utilizing Angular 2 templates to dynamically create assets. Below is a snippet of sample code: <a-assets> <div *ngFor="let scene of floorData.scen ...

Can an entire application built with a combination of PHP, JavaScript, and HTML be successfully converted to Angular 7?

After creating a complex application that heavily relies on JavaScript, PHP, HTML, and numerous AJAX calls, I am considering migrating the entire codebase to Angular 7. Is it feasible to achieve this transition without requiring a complete rewrite in Ang ...

Is there a way to refactor the onAuthStateChanged function from useEffect in firebase to a class component?

Below is the code snippet used in the function component: useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { setIsLoggedIn(!!user); }); return () => { unsubscribe(); }; }); And here is ...

What is the best way to organize a redux state to meet these specific needs?

In managing a complex web application state, it is crucial to keep track of multiple elements such as selected items and display IDs. The application may house several instances of these "States" with only one being active at any given time. For instance, ...