textarea绑定与下拉角2

时间:2017-09-07 11:29:18

标签: angular angular2-template angular2-forms angular2-directives

我有一个textarea和一个下拉列表。我想要在textarea中输入的任何字符串,该字符串将作为选项出现在下拉列表中。假设我输入textarea为'zcxvbnuyt',然后按'enter'后,该字符串将成为下拉选项。

我必须在服务器上发送的选项必须有一个字符串,其中\ n作为多个选项之间的分隔符。

这是我的HTML文件:

  

app.component.html

<div class="col-sm-6">
     <textarea rows="4" 
               cols="50"
               class="form-control input-sm" 
               id="Choices" 
               [(ngModel)]="model.Choices">
     </textarea>
 </div>


<div class="col-sm-6">
     <select class="form-control input-sm" 
          [(ngModel)]="model.DefaultValue" 
          [ngModelOptions]="{standalone: true}"
          required>
          <option *ngFor="let c of defaultOptions" [ngValue]="c.value">{{c.value}}</option>
     </select>
</div>
  

app.component.ts

 export class model{
            Choices: string;
            DefaultValue:string;
    }

 defaultOptions= [
                { value: 'dummy1' },
                { value: 'dummy2' }
        ];

1 个答案:

答案 0 :(得分:1)

  

HTML

<div class="col-sm-6">
<textarea rows="4"
    cols="50"
    class="form-control input-sm"
    id="Choices"
    (keypress)="checkForNewLine($event.keyCode)" [(ngModel)]="model.Choices">
</textarea>
</div>


<div class="col-sm-6">
<select class="form-control input-sm"
[(ngModel)]="model.SelectedValue"
[ngModelOptions]="{standalone: true}"
required>
    <option *ngFor="let choice of defaultOptions" [ngValue]="choice.value">{{choice.value}}</option>
</select>

  

打字稿

checkForNewLine(keycode){
if (keycode === 13 || keycode == 8 || keycode == 46){
    this.defaultOptions = [];
    let tmp = model.Choices.split('\n');
    tmp.forEach((data, index) => {
            this.defaultOptions.push({value: data});
        });
}