2016-12-15 38 views
1

我确认表并希望添加ng2-selectAngular2 - 打字稿:添加一个数组来使用角2 FormControl

这是我的代码,角& HTML

submit.component.ts 

    . . . 

    private city = new FormControl("", Validators.required); 
    . . . 

    ngOnInit() { 
    this.getMelks(); 

    this.addPropertyForm = this.formBuilder.group({ 
     . . . 
     city: this.city, 
    . . . 
    }); 
    } 

submit.component.html

<div class="form-group"> 
       <input class="form-control" type="text" name="city" [(ngModel)]="melk.city" placeholder="city" min="0" required> 
</div> 

我想要的代码添加:

Angular

public city:Array<string> = ['NY','CA' ,'LA']; 

HTML

<label>City</label> 
     <ng-select [allowClear]="false" 
       [items]="city" 
       [disabled]="disabled" 
       (data)="refreshValue($event)" 
       (selected)="selected($event)" 
       (removed)="removed($event)" 
       (typed)="typed($event)" 
       placeholder="Choose the city"> 
     </ng-select> 

现在,我怎么添加NG2选我input和在FormControl?

+0

你想做什么?目前还不清楚你想如何添加选择到输入... – smnbbrv

回答

0

试试这个,希望它与兼容的formBuilder并让你可以把当前值:

<form class="form-group" [formGroup]="cityForm"> 
       <input class="form-control"formControlName="city" type="text" name="city" [(ngModel)]="melk.city" placeholder="city" min="0" required> 



<label>City</label> 
     <ng-select formControlName="citySelect" 
[allowClear]="false" 
       [items]="city" 
       [disabled]="disabled" 
       (data)="refreshValue($event)" 
       (selected)="selected($event)" 
       (removed)="removed($event)" 
       (typed)="typed($event)" 
       placeholder="Choose the city"> 
     </ng-select> 
</form> 
1

一个解决办法,我采用的是创建一个隐藏的输入正下方NG-选择和一个同步它ngModel。例如

<label>City</label> 
<ng-select #cityModel 
     [allowClear]="false" 
     [items]="city" 
     [disabled]="disabled" 
     (data)="refreshValue($event)" 
     (selected)="selected($event)" 
     (removed)="removed($event)" 
     (typed)="typed($event)" 
     placeholder="Choose the city"> 
    </ng-select> 
    <input [hidden]="true" type="text" [(ngModel)]="cityModel" name="cityModel" [formControl]="city"> 

submit.component.ts

. . . 

    private city = new FormControl("", Validators.required); 
    private cityModel; 

    . . . 

    selected = (selectedCity) => { 
     this.cityModel = value; 
     this.city.markAsDirty(); 
    } 
    removed =() => { 
     this.cityModel = null; 
     this.city.markAsDirty(); 
    } 

虽然这个,如果你做的形式控制一些动作没有帮助。像city.disable(),因为你会在隐藏的元素上做这件事。

我也有PR来解决这个问题https://github.com/valor-software/ng2-select/pull/758