2017-02-20 2 views
1

Я создал пользовательский элемент radio buttons и должен передать значение в родительскую форму. Но я получил сообщение об ошибке: Cannot find control with unspecified name attribute.Angular2 Пользовательские радиокнопки dont work

шаблон Родитель:

<form #f="ngForm"> 
    <radio name="radioParent" [data]="data" ngDefaultControl [(ngModel)]="dataOut"></radio> 
</form> 

Детский компонент:

import { 
    Component, Input, forwardRef, ElementRef, Renderer 
} from '@angular/core'; 
import { 
    FormControl, 
    NG_VALUE_ACCESSOR, NG_VALIDATORS, ControlValueAccessor 
} from '@angular/forms'; 


@Component({ 
    selector: 'radio', 
    template: ` 
    <ul> 
     <li *ngFor="let item of data"> 
     <label> 
      <input type="radio" name="radio1" 
      [value]="item.id" 
      [formControl]="childControl" 
      (input)="fn($event.target.value)" 
      > 
      <p>{{ item.title }}</p> 
     </label> 
     </li> 
    </ul> 
    `, 
    providers: [ 
    { 
     provide: NG_VALUE_ACCESSOR, 
     useExisting: forwardRef(() => MyChild), 
     multi: true 
    }, 
    { 
     provide: NG_VALIDATORS, 
     useExisting: forwardRef(() => MyChild), 
     multi: true 
    } 
    ] 
}) 

export class MyChild implements ControlValueAccessor { 
    @Input() data: any; 
    out: any; 


    fn: (value:any) => void; 

    validateFn: any =() => {}; 

    constructor(private _renderer: Renderer, private _elementRef: ElementRef) {} 

    writeValue(value: any): void { 
    this._renderer.setElementProperty(this._elementRef, 'checked', value == this._elementRef.nativeElement.value); 
    } 
    registerOnChange(fn: (value: any) => void) { 
    this.onChange = fn; 
    } 
    registerOnTouched() {} 

} 

И в plunker: https://plnkr.co/edit/hkk0CANKWRmys9R4gZg1?p=preview

ответ

1

Изменено несколько вещей:

  • использование item.value вместо item.id
  • удален [formControl]="childControl", в вашем компоненте нет свойства childControl!
  • использование (click) вместо (input)
  • удалены provide: NG_VALIDATORS, это приводит к ошибкам! вам нужно настроить его правильно, то не копировать пасту из provide: NG_VALUE_ACCESSOR

рабочую демо: https://plnkr.co/edit/iYQF2Z6MVh0aeMz1nGLG?p=preview

@Component({ 
    selector: 'radio', 
    template: ` 
    <ul> 
     <li *ngFor="let item of data"> 
     <label> 

      <!-- [formControl]="childControl" causes errors.. there is no property called 'childControl' in this component.. --> 
      <!-- [value]="item.value" instead of [value]="item.id" !! --> 

      <input type="radio" name="radio1" 
      [value]="item.value" 

      (click)="onChange($event.target.value)"> 

      <!-- use (click) instead of (input) --> 

      <span>{{ item.title }}</span> 
     </label> 
     </li> 
    </ul> 
    `, 
    providers: [ 
    { 
     provide: NG_VALUE_ACCESSOR, 
     useExisting: forwardRef(() => MyChild), 
     multi: true 
    } 
    /*, causes errors !! 
    { 
     provide: NG_VALIDATORS, 
     //useExisting: forwardRef(() => MyChild), => not right !! do not just copy and paste stuff around .. ! 
     // should be something like this: 
     useValue: validateEmail, // <-- your validation function ! 
     // see this article: https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html 
     multi: true 
    } 
    */ 
    ] 
}) 
+0

Работа Плюккеровы [https://plnkr.co/edit/hkk0CANKWRmys9R4gZg1?p=preview](https : //plnkr.co/edit/hkk0CANKWRmys9R4gZg1 р = предпросмотр) – MikeS