gpt4 book ai didi

angular - 添加了未显示的 ng-select 响应式(Reactive)表单验证消息

转载 作者:行者123 更新时间:2023-12-02 00:11:01 25 4
gpt4 key购买 nike

我向 ng-select 组件添加了一条错误消息,以在它变脏且未选择值时显示错误消息。但是错误消息没有显示。但验证有效。

https://ng-select.github.io/ng-select/

<form [formGroup]="itemForm" (ngSubmit)=onSubmitForm()>
<div class="form-group col">
<label for="pack_size">Supplier</label>
<ng-select
bindLabel="supplier"
placeholder="Select Supplier"
formControlName="supplier"
[ngClass]="{ 'is-invalid': supplier.invalid && supplier.touched }"
>
<ng-option *ngFor="let supplier of suppliers" [value]="supplier.id">
{{supplier.description}}
</ng-option>
</ng-select>
<div *ngIf="supplier.invalid && supplier.touched" class="invalid-feedback">
<div *ngIf="!!supplier.errors.required">Supplier is required</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit"
[disabled]="itemForm.invalid">Add</button>
</form>

已添加的 CSS 类

ng-select.ng-invalid.ng-touched .ng-select-container {
border-color: #dc3545;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 3px #fde6e8;
}

根据要求为表单函数创建 ts 文件

itemForm: FormGroup;

constructor(
private _fb: FormBuilder,
) {}

ngOnInit() {
this.submitted = false;
this.buttonValue = 'Add';
this.loadOthers();
this.itemsLoad();
this.itemForm = this._fb.group({
id: [null],
name: [null, Validators.required],
pack_type: [null, Validators.required],
pack_size: [null, Validators.required],
supplier: [null, Validators.required],
item_category: [null, Validators.required],
});
}


get id() {
return this.itemForm.get('id');
}

get name() {
return this.itemForm.get('name');
}

get pack_type() {
return this.itemForm.get('pack_type');
}

get pack_size() {
return this.itemForm.get('pack_size');
}

get supplier() {
return this.itemForm.get('supplier');
}

get item_category() {
return this.itemForm.get('item_category');
}

最佳答案

请像这样尝试

<form [formGroup]="itemForm" (ngSubmit)=onSubmitForm()>
<div class="form-group col">
<label for="pack_size">Supplier</label>
<ng-select
bindLabel="supplier"
placeholder="Select Supplier"
formControlName="supplier"
[ngClass]="{ 'is-invalid': itemForm.get('supplier').invalid && itemForm.get('supplier').touched }"
>
<ng-option *ngFor="let supplier of suppliers" [value]="supplier.id">
{{supplier.description}}
</ng-option>
</ng-select>
<div *ngIf="itemForm.get('supplier').invalid && itemForm.get('supplier').touched" class="invalid-feedback">
<div *ngIf="!!itemForm.get('supplier').hasError('required')">Supplier is required</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit"
[disabled]="itemForm.invalid">Add</button>
</form>

您需要将供应商更改为itemForm.get('supplier')

我不确定,但我认为您也需要更改类(class)。

关于angular - 添加了未显示的 ng-select 响应式(Reactive)表单验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59091313/

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