Can a form component be recycled through the use of inheritance?

Greetings to the Stackoverflow Community,

As I delve into this question, I realize that examples on this topic are scarce. Before diving into specifics, let me outline my strategy.

I currently have three pages with numerous FormGroups that overlap significantly. Their differences are minor, usually just one or two FormControls. While the easy solution would be to duplicate the entire component and add the required control, I find this approach impractical and disorderly. How can I tackle this issue effectively? Furthermore, I am seeking resources on inheritance in Angular as a whole. Despite browsing through official documentation and courses, such as the hero course, I have not come across relevant information on this subject.

Answer №1

It surprised me how simple it actually was, contrary to what I had assumed initially. I decided to create a FormBuilder class that would handle all the common controls used in different forms. By extending this FormBuilder class, any component can easily create a form like this.

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Form } from '../form';

@Component({
  selector: 'app-invoices',
  templateUrl: './invoices.component.html',
  styleUrls: ['./invoices.component.scss']
})
export class InvoicesComponent extends FormBuilder {

  constructor() { 
    super()

    this.createForm();
  }
}

With just a simple line of code, I could add the necessary FormControls to my form:

this.queryForm.addControl('newControl', new FormControl(''))

This made it extremely easy to update the HTML code of the component with very minimal changes required.

Answer №2

If you want to achieve this, content projection is the way to go.

Consider a scenario where you have a FormGroup component containing two input fields. This component will also include ng-content allowing other components to insert their own HTML.

@Component({
    selector: 'my-form-group',
    template: `
        Type something : <input type="text"/> 
        Select something: <select> ... </select>
        Insert your own stuff: <ng-content></ng-content>
    `
})
export class FormGroupComponent {}

@Component({
    selector: 'my-form-group-radio',
    template: `
        <my-form-group>
             <input type="radio" name="myOption" value="1" />
             <input type="radio" name="myOption" value="2" />
        </my-form-group>
    `
})
export class FromGroupRadioComponent {}

This approach allows for the reusability of FormGroupComponent multiple times. Different components can be created and project different content as needed.

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

Angular 5 APP_INITIALIZER: Provider parse error - Cyclic dependency instantiation not possible

I am utilizing the APP_INITIALIZER token to execute a task upon page load before my Angular application is initialized. The service responsible for this functionality relies on another service located within my CoreModule. The issue at hand seems to be ab ...

Why should TypeScript interfaces be utilized in Angular services for defining type information?

What are the benefits of creating an interface for an Angular service as opposed to simply exporting the service class and using that for type information? For example: class Dashboard { constructor(ui: IUiService){} } vs class Dashboard { cons ...

Issues with Angular updating the *ngFor Loop

I'm looking to showcase a lineup of upcoming concerts in my HTML, sourced from a web API (which is functioning correctly). The API is encapsulated within a ConcertService: @Injectable({ providedIn: 'root' }) export class ConcertService { ...

Is the slow loading time of the Dev browser due to the large size of the vendor.js file

When using Angular 8.0, my browser takes around 15 seconds to load with ng serve. However, the browser only takes about 4 seconds to load when using ng serve --prod. One of the main reasons for the slow loading time in development is a vendor.js file tha ...

How can I determine if an Angular library is compatible with the specific version of Angular that my application is utilizing?

My Angular 8 application is currently running on a version that's quite outdated compared to the latest release of Angular. When it comes to incorporating Angular libraries, how can I determine if they are compatible with Angular 8? Is there a strict ...

A guide on updating a MySQL table using a JSON object in Node.js

I have a JSON Object and need to UPDATE a mySQL table without listing all of the keys individually For an INSERT operation, I use the following code: var arrayValue = Object.keys(obj).map(function(key) { return String("'"+obj[key]+"'"); ...

Changing the Month Label Format from Short (MMM) to Long (MMMM) in Angular Material Datepicker

I am looking to customize the month labels in Angular Material datepicker. By default, the month view displays in MMM format and I want to change it to MMMM using custom MatDateFormats. export const APP_DATE_FORMATS: MatDateFormats = { parse: { dat ...

Generating a d.ts file for images in Typescript using automation techniques

Currently, I am working on a React application that utilizes TypeScript and webpack. I am aware that in TypeScript, when importing an image file, it is necessary to create a d.ts file in the current directory and include the following code: // index.d.ts ...

Having trouble getting the reset select function to work

I'm in the process of developing a website where I'm facing an issue with resetting my form that is constructed using jQuery Uniform. Despite my efforts, I am unable to successfully reset it. Below is the header code snippet: $j(function() { ...

Trouble accessing JSON object keys in Angular2 (rc.6)

Embarking on my initial Angular2 (rc.6) endeavor. I've managed to send a JSON object to a component successfully, but I'm facing difficulties accessing its key values in the template. SERVICE (excerpt): @Injectable() export class SongService { ...

The type 'TaskListProps[]' cannot be assigned to type 'TaskListProps'

I'm struggling with handling types in my TypeScript application, especially with the TaskListProps interface. export default interface TaskListProps { tasks: [ { list_id: string; title: string; description: string; status ...

The improved approach to implementing guards in Angular

I am currently looking for the most effective way to utilize Angular "guards" to determine if a user is logged in. Currently, I am checking if the token is stored. However, I am wondering if it would be better to create an endpoint in my API that can verif ...

Tips for managing transitions when the indicator is clicked by the user

I'm looking for a way to implement logic that determines whether or not a user can change the step by clicking on the indicator (the step number). I need a callback function that triggers every time there is a step change, but also allows me to preven ...

What is the best way to approach writing a shared value that is utilized across multiple files in Angular?

I am currently implementing Angular for the front end of my project. One challenge I'm facing is managing a single value, such as a 'role id', that needs to be used in multiple .ts files within Angular. Can anyone suggest an efficient way ...

Increment counter when a key is pressed in Angular 4 and decrement when the backspace key is pressed

As a beginner in Angular, my goal is to create a feature where: The character count in a label increases as text is entered into a textarea. When the backspace key is pressed, the counter should decrease. If the user attempts to enter more characters tha ...

Leveraging jQuery within Angular 6

In the 'src' folder of my Angular app, there is a simple JavaScript file named 'my.js' slideDown(id) { $('#' + id).slideToggle(); } I am trying to figure out how to call this function by using the following code: <div ...

Tips for effectively typing a collection of React wrappers in TypeScript

I encountered a situation in my team's application where we need the ability to dynamically compose component wrappers (HOCs) without prior knowledge of all the wrapper interfaces. This is mostly needed for swapping out context providers when renderin ...

Utilizing a variable to pass props to a component (instead of a static component) within React Router 5

In react-router 5, you can pass props to a child component in this way: <Route path="/" exact render={ props => <MyPage title={myTitle} dataPath={myDataPath} {...props} />} /> However, I am using a route model in my ...

Is there a way to switch an element across various pages within Ionic 3?

Is it possible to exchange information between two pages using logic? I have successfully implemented a checklist, but I am unsure how to add a success/error icon next to the Room name on the 'verifyplace.html' page after invoking the goToNextPa ...

Refreshing rows in ngx-datatable

Just started using ngx-datatable (version 11) with Angular-5 and encountered an issue. When loading rows during ngInit, everything works fine. However, when lazy-loading due to a user search request, the table shows the correct total number of rows but onl ...