1

我已经动态创建了表单,我遵循了 angular2 cookbook 中的动态表单教程:教程。我在那里创建了我的自定义动态控件“RadioTextboxField”,其中包含单选按钮列表,并且每个单选按钮都可以有关联的文本框控件。

基类:

export class QuestionBase<T>{
value: T;
key: string;
label: string;
required: boolean;
order: number;
controlType: string;

constructor(options: {
  value?: T,
  key?: string,
  label?: string,
  required?: boolean,
  order?: number,
  controlType?: string
  } = {}) 

 {
   this.value = options.value;
   this.key = options.key || '';
   this.label = options.label || '';
   this.required = !!options.required;
   this.order = options.order === undefined ? 1 : options.order;
   this.controlType = options.controlType || '';
  }
}

RadioTexbox 字段:

import { QuestionBase } from './question-base';

export class RadioTextboxField extends QuestionBase<string> {
controlType = 'textbox-radio';
labelRadio: { label: string, isTextBox: boolean, value:any }[] = [];
radioVal:string;

 constructor(options: {} = {}) {
     super(options);
     this.labelRadio = options['labelRadio'] || '';
     this.radioVal = options['radioVal'] || '';
  }
}

其中labelRadio:包含在控件中的单选按钮和可选文本框的列表(标签:显示在单选按钮旁边的标签, isTextBox:如果显示文本框则指定, 值:如果文本框不可见,则为单选按钮指定值,否则应取文本框中的值)。这是我的表格: 表格:

<div [formGroup]="form">
  <label [attr.for]="question.key">{{question.label}}</label>
   <div [ngSwitch]="question.controlType">

   <input *ngSwitchCase="'textbox'" [formControlName]="question.key"
        [id]="question.key" [type]="question.type">

   <select [id]="question.key" *ngSwitchCase="'dropdown'" 
    [formControlName]="question.key">
    <option *ngFor="let opt of question.options" [value]="opt.key">
    {{opt.value}}</option>
    </select>

    <div *ngSwitchCase="'textbox-radio'">
      <div *ngFor="let opts of question.labelRadio; let j=index">

      <!--  my radio-button control !-->
      <input type="radio" [id]="question.key" [value]="opts.value" (click)="question.radioVal=opts.value;" [checked]="question.radioVal==opts.value">     
       <label [attr.for]="question.key" >{{opts.label}}</label>
       <input [id]="'text'+j" *ngIf="opts.isTextBox"
        [type]="text" class="form-control input-sm" [readonly]="question.radioVal!=opts.value" [formControlName]="question.key" [value]="opts.isTextBox ? question.key : opts.value">
     </div>
</div> 
<div class="errorMessage" *ngIf="!isValid">{{question.label}} is 
required</div>

我无法从该控件读取值,从单选按钮或可选的从文本框中获取值(如果显示)。如果未选中与之关联的单选按钮,我还想禁用文本框。这是 plunker 上完整代码的链接:plunker 请帮助我,我不知道如何解决这个问题。

4

0 回答 0