gpt4 book ai didi

javascript - Angular2-TypeScript : Adding an array to FormControl

转载 作者:太空宇宙 更新时间:2023-11-04 16:14:44 27 4
gpt4 key购买 nike

我有使用 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,
. . .
});
}

提交.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-select 添加到我的 input 和 FormControl 中?

最佳答案

我使用的一个解决方法是在 ng-select 正下方创建一个隐藏输入,并将其与 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">

提交.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

关于javascript - Angular2-TypeScript : Adding an array to FormControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41167035/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com