npm package: @ngxform/platform
Description: A powerful Angular library for dynamically rendering reactive forms with customizable components.
Latest version: 20.0.1

# NgxForm Platform

A powerful Angular library for dynamically rendering reactive forms with customizable components.

## Overview

NgxForm Platform provides a declarative way to build complex Angular reactive forms by mapping form controls to UI components. It allows you to define form templates and render them dynamically, making form creation more maintainable and reusable.

## Features

- 🚀 Dynamic form rendering
- 🎯 Type-safe form templates
- 🔧 Customizable component options
- 📝 Support for FormGroup, FormArray, and FormControl
- 🎨 Flexible styling and layout options
- ✅ Built-in form validation handling

## Installation

```bash
npm install @ngxform/platform
```

## Peer Dependencies

- `@angular/core`: ^20.3.0
- `@angular/forms`: ^20.3.0
- `rxjs`: ~7.8.0

## Quick Start

### 1. Import Required Modules

```typescript
import { Component, inject, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { NgxFormManager, NgxFormrAnchorComponent } from '@ngxform/platform';
import { TextControlComponent } from '@ngxform/controls'; // Your custom control components
```

### 2. Setup Component

```typescript
@Component({
  selector: 'app-demo',
  imports: [ReactiveFormsModule, NgxFormrAnchorComponent],
  template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <ngx-form-anchor #anchor></ngx-form-anchor>
      <button type="submit">Submit</button>
    </form>
  `
})
export class DemoComponent implements OnInit {
  private fb = inject(FormBuilder);
  private ngxFormManager = inject(NgxFormManager);
  protected form!: FormGroup;
  
  @ViewChild('anchor', { static: true }) anchor!: NgxFormrAnchorComponent;

  ngOnInit(): void {
    // Create reactive form
    this.form = this.fb.group({
      name: [''],
      email: ['', [Validators.email, Validators.required]],
    });

    // Define form template
    const ngxForm = this.ngxFormManager.init(this.form, {
      name: {
        component: TextControlComponent,
        option: {
          label: 'Name',
          placeholder: 'Enter your name',
          className: ['form-field']
        }
      },
      email: {
        component: TextControlComponent,
        option: {
          label: 'Email',
          placeholder: 'Enter your email',
          className: ['form-field']
        }
      },
    });

    // Render the form
    this.ngxFormManager.render(ngxForm, this.anchor.viewContainerRef);
  }

  onSubmit(): void {
    if (this.form.invalid) {
      this.ngxFormManager.markAllAsDirty(this.form);
    } else {
      console.log(this.form.value);
    }
  }
}
```

## API Reference

### NgxFormManager

The main service for managing form instances and rendering.

#### Methods

##### `init(control: AbstractControl, template: Template): NgxFormInstance`
Initializes a form instance with the given control and template.

**Parameters:**
- `control`: Angular reactive form control (FormGroup, FormArray, or FormControl)
- `template`: Template configuration defining how controls should be rendered

**Returns:** NgxFormInstance object

##### `render(instance: NgxFormInstance | string, viewContainerRef: ViewContainerRef, controls?: string[]): void`
Renders the form instance into the specified view container.

**Parameters:**
- `instance`: Form instance or instance name
- `viewContainerRef`: Angular ViewContainerRef where components will be rendered
- `controls`: Optional array of control names to render (renders all if not specified)

##### `markAllAsDirty(control: AbstractControl | string, options?: object): void`
Marks all form controls as dirty to trigger validation display.

**Parameters:**
- `control`: Form control or instance name
- `options`: Optional configuration for marking dirty

##### `watch(name: string, control: AbstractControl): void`
Watches a form control with the given name.

##### `get(name: string): NgxFormInstance | undefined`
Retrieves a form instance by name.

##### `cast(name: string, template: Template): void`
Updates the template for an existing form instance.

### NgxFormrAnchorComponent

A component that provides an anchor point for dynamically rendered form controls.

```typescript
@Component({
  selector: 'ngx-form-anchor',
  template: '',
  standalone: true
})
```

Use this component in your template where you want the form controls to be rendered:

```html
<ngx-form-anchor #anchor></ngx-form-anchor>
```

## Template Configuration

### Form Control Template

```typescript
interface FormControlTemplate {
  component: NgxFormManagerComponent<NgxFormManagerControlOption>;
  option: NgxFormManagerControlOption;
}
```

**Example:**
```typescript
{
  component: TextControlComponent,
  option: {
    label: 'Username',
    placeholder: 'Enter username',
    nzSize: 'large',
    className: ['ant-col', 'ant-col-xs-24', 'ant-col-sm-12']
  }
}
```

### Form Group Template

For nested form groups, define templates for each control:

```typescript
const formTemplate = {
  personalInfo: {
    firstName: {
      component: TextControlComponent,
      option: { label: 'First Name' }
    },
    lastName: {
      component: TextControlComponent,
      option: { label: 'Last Name' }
    }
  },
  contactInfo: {
    email: {
      component: TextControlComponent,
      option: { label: 'Email', type: 'email' }
    }
  }
};
```

### Form Array Template

For form arrays, provide an array of templates:

```typescript
const formArrayTemplate = [
  {
    component: TextControlComponent,
    option: { label: 'Item 1' }
  },
  {
    component: TextControlComponent,
    option: { label: 'Item 2' }
  }
];
```

## Advanced Usage

### Partial Rendering

You can render only specific controls by passing a controls array:

```typescript
// Only render 'name' and 'email' controls
this.ngxFormManager.render(
  ngxForm, 
  this.anchor.viewContainerRef, 
  ['name', 'email']
);
```

### Dynamic Form Management

```typescript
// Watch a form control
this.ngxFormManager.watch('userForm', this.form);

// Update template later
this.ngxFormManager.cast('userForm', newTemplate);

// Render with updated template
this.ngxFormManager.render('userForm', this.anchor.viewContainerRef);
```

### Custom Control Components

Create custom control components by implementing `NgxFormManagerComponent`:

```typescript
@Component({
  selector: 'app-custom-input',
  template: `
    <label>{{ option.label }}</label>
    <input [formControl]="control" [placeholder]="option.placeholder">
  `
})
export class CustomInputComponent implements NgxFormManagerComponent<any> {
  control!: AbstractControl;
  option!: any;
}
```

## Error Handling

The library provides built-in error handling and validation display:

```typescript
onSubmit(): void {
  if (this.form.invalid) {
    // This will mark all controls as dirty and show validation errors
    this.ngxFormManager.markAllAsDirty(this.form);
    return;
  }
  
  // Form is valid, proceed with submission
  this.processForm(this.form.value);
}
```

## Best Practices

1. **Type Safety**: Define interfaces for your form options to ensure type safety
2. **Component Reusability**: Create reusable control components for common input types
3. **Validation**: Use Angular's built-in validators and custom validators
4. **Performance**: Use `OnPush` change detection strategy for better performance
5. **Testing**: Write unit tests for your form templates and control components

## Examples

### Complete Form Example

```typescript
@Component({
  selector: 'app-user-form',
  imports: [ReactiveFormsModule, NgxFormrAnchorComponent],
  template: `
    <form [formGroup]="userForm" (ngSubmit)="onSubmit()">
      <div class="form-container">
        <ngx-form-anchor #anchor></ngx-form-anchor>
      </div>
      <div class="form-actions">
        <button type="submit" [disabled]="userForm.invalid">
          Submit
        </button>
      </div>
    </form>
  `
})
export class UserFormComponent implements OnInit {
  private fb = inject(FormBuilder);
  private ngxFormManager = inject(NgxFormManager);
  
  userForm!: FormGroup;
  @ViewChild('anchor', { static: true }) anchor!: NgxFormrAnchorComponent;

  ngOnInit(): void {
    this.userForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      age: ['', [Validators.required, Validators.min(18)]],
      bio: ['']
    });

    const formTemplate = {
      name: {
        component: TextControlComponent,
        option: {
          label: 'Full Name',
          placeholder: 'Enter your full name',
          nzSize: 'large',
          className: ['form-field', 'required']
        }
      },
      email: {
        component: TextControlComponent,
        option: {
          label: 'Email Address',
          placeholder: 'Enter your email',
          type: 'email',
          nzSize: 'large',
          className: ['form-field', 'required']
        }
      },
      age: {
        component: TextControlComponent,
        option: {
          label: 'Age',
          placeholder: 'Enter your age',
          type: 'number',
          nzSize: 'large',
          className: ['form-field', 'required']
        }
      },
      bio: {
        component: TextareaControlComponent,
        option: {
          label: 'Biography',
          placeholder: 'Tell us about yourself',
          rows: 4,
          className: ['form-field']
        }
      }
    };

    const ngxForm = this.ngxFormManager.init(this.userForm, formTemplate);
    this.ngxFormManager.render(ngxForm, this.anchor.viewContainerRef);
  }

  onSubmit(): void {
    if (this.userForm.invalid) {
      this.ngxFormManager.markAllAsDirty(this.userForm);
    } else {
      console.log('Form submitted:', this.userForm.value);
      // Handle form submission
    }
  }
}
```

## Contributing

Please read our contributing guidelines before submitting pull requests.

## License

This project is licensed under the MIT License.