2016-12-15 47 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