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
931 views
in Technique[技术] by (71.8m points)

angular - ngModel: No value accessor for ''

I'm creating a custom element in Angular 2.0 (<my-select>), and when I include the ngModel attribute on the component, I'm immediately hit with the following error:

EXCEPTION: No value accessor for '' in [myModel in App@0:195]

Here's a plunker: http://plnkr.co/edit/wlkPWcB92YZASCwCnmcw?p=preview

(Open console to view error)

If you simply comment out the following line from src/app.ts, the component will render appropriately:

'[ngModel]="myModel"'

I've done the following:

  1. Imported {FORM_DIRECTIVES} from 'angular2/common'
  2. Included FORM_DIRECTIVES in the directives portion of the @Component
  3. Initialized myModel

What am I missing here?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I take this error for 2 reasons:

1) Component has to attach itself as a value accessor, like:

@Component({
  selector: 'ace-editor',
  template: `<div class="ng2-ace-editor"></div>`,
})

export class AceEditor implements OnInit, ControlValueAccessor {

  constructor(private element: ElementRef, @Optional() ngControl: NgControl) {
    if (ngControl) {
      ngControl.valueAccessor = this;
    }
  }

2) You haven't to mix deprecated and new forms. If you use a new API add to your main.ts:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { disableDeprecatedForms, provideForms } from '@angular/forms';

import { AppComponent } from './app.component';

bootstrap(AppComponent, [
  disableDeprecatedForms(),
  provideForms()
])
.catch((err: any) => console.error(err));

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

...