我有使用Angular 2的验证表单,并希望将ng2-select
添加到其中
这是我的代码,Angular& 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>
现在我如何在我的input
和FormControl中添加ng2-select?
答案 0 :(得分:1)
我使用的一种解决方法是在ng-select下创建一个隐藏输入,并使用ngModel同步它。 e.g。
<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
答案 1 :(得分: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>