Exploring the utilization of ngModel within a tag that is selector-based

As a newcomer to Angular 2, I have encountered a challenge with forms that contain multiple text boxes, checkboxes, labels, and drop-downs. When including all these controls in my HTML, the page becomes too long. To address this issue, I would like to create separate components for each control and then use them as selectors within my main component's HTML file.

However, I am unsure how to access the value of each control if I have 10 text boxes, 10 drop-down menus, and multiple labels. Does anyone have experience or knowledge regarding this matter?

If I were to use ngModel for each separate component, how would I go about accessing the values for each individual control?

Answer â„–1

Create your own custom component with ease

@Component({
  selector: 'my-textinput',
  template: `<div class="form-group">
                    <label><ng-content></ng-content>
                        <input [(ngModel)]="value"
                                class="form-control"
                                (blur)="onBlur()" >
                    </label>
                </div>`,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => TextInputCellEditorComponent),
      multi: true
    }
  ]
})
export class TextInputCellEditorComponent implements ControlValueAccessor, OnInit, OnDestroy {

  private value: any;

  constructor(private el: ElementRef) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
  }

  /**
   * Set the editor's value
   */
  public writeValue(value:any) {
    this.value = value;
  }

  /**
   * Subscribe to changes
   */
  public registerOnChange(fn) {

  }

  /**
   * Register touch events
   */
  public registerOnTouched(fn) {

  }

  ngOnDestroy() {

  }
}

Integrate this custom component into your project effortlessly

<form>
    <my-textinput name="anyValue"
                  [(ngModel)]="anyModel">
    </my-textinput>
  </form>

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

What's Causing the UNMET PEER DEPENDENCY Error in Angular 8 with @angular/[email protected]?

After updating to the latest version of Angular 8, everything seems to be working fine without any issues. However, I am seeing some strange messages when running npm list after completing npm install: UNMET PEER DEPENDENCY @angular/<a href="/cdn-cgi/ ...

Tips for updating a session cookie in nestjs

After successfully setting up session authentication using NestJS, I have always relied on JWT and set a short expiration time for access tokens. In order to obtain a new access token, the frontend must refresh it. Now, I am facing the challenge of implem ...

Is it possible to implement Typescript validation for the properties of an object that is returned from a callback function passed to a generic React

TS offers a lot of possibilities, but sometimes it can be challenging to achieve what you want. This is the basic structure of my component: export interface DataTableProps<T> { data: { id: string; view: T; }[]; cellModifications?: ( ...

Guide to setting a default value for a select option in Angular 2+

I am having trouble setting a default option in my select box using the html selected property. I want the selected option to be assigned to StartingYear, but currently it's not working as expected. <select [(ngModel)]="StartingYear"> < ...

Tips for troubleshooting the error message: "The relative import path "$fresh/dev.ts" is not prefaced with / or ./ or ../"

My editor is showing a TypeScript error for a Deno module I am working on. The import path "$fresh/dev.ts" should be prefixed with / or ./ or ../ I have an import_map.json file set up with the following content. { "imports": { "$fre ...

Angular 5 displaying error message: "The requested resource does not have the 'Access-Control-Allow-Origin' header."

I encountered an issue in Angular 5 while attempting to consume a POST REST method. The error message reads: The preflight request response failed the access control check: The requested resource does not have the 'Access-Control-Allow-Origin' h ...

Can TypeORM create an entity for a many-to-many relationship that functions like ActiveRecord's join table concept?

Consider a scenario where there is a Guardian entity connected to a Student entity. The goal is to establish their many-to-many relationship in TypeORM by introducing a new entity called StudentGuardianRelationship. This intermediary entity serves the purp ...

Error message indicating that the Angular validator function is not properly defined

I'm currently working with Angular FormBuilder and implementing my own validation logic. In my formBuilder configuration, I have defined the following: this.form = this.formBuilder.group({ password: ['', [Validators.required, this.matcher ...

Angular List Selector: A versatile multiple selection component with a stylish list design

I'm in need of a select component similar to the one shown in https://i.sstatic.net/mo6NH.png The issue is that Material Angular doesn't have this specific component, so I opted to use the default HTML select inside my component. Everything was ...

Using React's useState hook with an empty array

interface Crumb { title: string; url: string; } interface Crumbies { crumbsArray: Crumb[]; } // component const [breadcrumbs, setBreadcrumbs] = useState<Crumbies>([]); I encountered an issue: TS2345: Argument of type 'never[]' is ...

When utilizing makeStyles in @mui, an error may occur stating that property '' does not exist on type 'string'

I am stuck with the code below: const useStyles = makeStyles(() => ({ dialog: { root: { position: 'absolute' }, backdrop: { position: 'absolute' }, paperScrollPaper: { overflow: 'visib ...

A step-by-step guide on bundling a TypeScript Language Server Extensions LSP using WebPack

Currently, I am working on a language server extension for vs-code that is based on the lsp-sample code. You can find the code here: https://github.com/microsoft/vscode-extension-samples/tree/master/lsp-sample My challenge lies in WebPacking the extension ...

Utilizing TypeScript Generics for Creating Arrays of Objects with Inherited Type Definitions

I'm exploring the concept of type inheritance for an array of objects, where one object's value types should inherit from another. While I'm unsure if this is achievable, it's definitely worth a try. Currently, I believe my best approac ...

Should mutators be encapsulated within a class contained in a JS Module for better code organization and maintainability?

In order to maximize functionality of our new product using JavaScript, we have implemented an Authentication module that manages a tokenPromise which is updated upon user logins or token refreshes. It seems imperative to allow for mutation in this process ...

Having trouble with combining two formgroups using concat in an Angular application

I have developed an angular form using reactive forms, with controls displayed on the left and right side. The controls on the right are labeled as "alternate" and are shown based on the selection of a radio button. To accommodate this, I have created two ...

Is it possible to access NgbdModalContent properties from a different component?

If I have a component with a template containing an Edit button. When the user clicks on it, I want to load another component as a dynamic modal template. The component is named ProfilePictureModalComponent and it includes the Edit button: (Angular code h ...

Encountering a 403 Error when Configuring POST Requests in Angular 6 Proxy

Currently troubleshooting a local Angular 6 application with the command ng serve --proxy-config proxy.conf.json. Here's a snippet of my proxy.conf.json file: (target has been changed for security purposes) { "/**": { "target": "http://my-main- ...

Communicating Between Children Components in Angular 2

Is there a way to achieve Child-Child communication in Angular2? While the Angular2 Documentation offers solutions for Parent-Child communication, I am curious about how children components nested within a parent can interact with each other. Can one child ...

Stopping Angular2 HTTP Requests - A Guide to Aborting or Cancelling Executing Requests

Currently, I am implementing an autocomplete feature for my search functionality. handleKeypress(searchValue){ // Code to make an AJAX request with the search value // .... } I am looking to cancel any previous HTTP requests each time a keypress ev ...

React: Why aren't class methods always running as expected?

I created a class component that retrieves a list of applications from an external API. It then sends a separate request for each application to check its status. The fetching of the applications works well, but there is an issue with the pinging process ...