Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ngModel with a custom control inside a form?

I created a component for handling select box, now when I put it in form tag after submitted form the result of the selection doesn't show up in console.

What's the problem with my code? how can I fix this?

  • testOption: is array of object I passed throw the select box with @Input.

here is select box component:

import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'input-select',
    template:`
      <div class="field-select">
        <span><icon name="select-arrow" size="10"></icon></span>
        <select name="{{name}}" class="field">
          <option value="0" disabled selected>{{label}}</option>
          <option *ngFor="let option of options" [ngValue]="option.value">{{option.name}}</option>
        </select>
      </div>
    `
})
export class InputSelectComponent implements OnInit {
    @Input() label: string;
    @Input() name: string;
    @Input() options;


    // testOptions = [
    //   {value:'test',name:'test2'},
    //   {value:'test',name:'test2'}
    // ];

    constructor() { }

    ngOnInit() {
      console.log(this.options);
     }

}

Usage in html:

<input-select label="test" name="select2" [options]="testOption"></input-select>

form html:

<form role="form" class="form" #f="ngForm" (ngSubmit)="onSubmit(f)">
    <input class="field" name="name" ngModel type="text" placeholder="n1">
    <input-select label="b2" name="select2" [options]="testObject"></input-select>
    <input class="field" name="building-type" type="text" ngModel placeholder="b3">
</form>

console log: (there is no select box value)

Object {name: "test", building-type: "tset" }
like image 499
Sajad Avatar asked Jan 30 '17 10:01

Sajad


1 Answers

I guess I got your problem now.

You want to implement ControlValueAccessor on your custom component to use it inside of a form with ngModel!?

Your component should look like this:

@Component({
   selector: 'ng2-input-select',
   template: `
      <div class="field-select">
        <select name="{{ name }}" class="field" [(ngModel)]="value" (ngModelChange)="_onChange($event)">
          <option value="" disabled selected>{{ label }}</option>
          <option *ngFor="let option of options" [value]="option.value">{{ option.name }}</option>
        </select>
      </div>
   `,
   providers: [
      { /* idk why or what this will do exactly.. but it works! ;) */
         provide: NG_VALUE_ACCESSOR,
         useExisting: forwardRef(() => SelectBoxComponent),
         multi: true
      }
   ]
})
export class SelectBoxComponent implements OnInit, ControlValueAccessor {
  @Input() label: string;
  @Input() name: string;
  @Input() options;
  @Input() value: string = '';

  // ControlValueAccessor implementation
  // ====================================

  // call if value was changed inside our component
  private _onChange = (_: any) => { };
  // call if input was "touched" .. !
  private _onTouched = () => { };

  // incoming change..
  public writeValue(val: any) {
    this.value = val;
  }

  public registerOnChange(fn: (_: any) => void): void { this._onChange = fn; }
  public registerOnTouched(fn: () => void): void { this._onTouched = fn; }
}

live-demo: https://plnkr.co/edit/imCJmCoJaeGQiUMcyBwz?p=preview

UPDATE

Using change detection in your form-component:

<ng2-input-select ngModel (ngModelChange)="selectBoxChanged($event)" label="b2" name="select2" [options]="testObject"></ng2-input-select>
like image 163
slaesh Avatar answered Oct 13 '22 02:10

slaesh