Reputation: 743
I have validation Form using Angular 2 and want to add ng2-select
to it
this is my code, 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>
the code i want to add :
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>
Now how can i add ng2-select to my input
and the the FormControl?
Upvotes: 1
Views: 1559
Reputation: 194
One workaround I've used is to create a hidden input right below ng-select and synced it with a 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();
}
Although this doesn't help if you do some action on the form control. Like city.disable()
because you would be doing that on the hidden element instead.
I also have a PR to address this issue https://github.com/valor-software/ng2-select/pull/758
Upvotes: 1
Reputation: 1095
try this, hopefully it's compatible with for formBuilder and allows you to grab current value:
<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>
Upvotes: 0