Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
940 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 Reply

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...