Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angular - 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" }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...