我正在尝试修补 ng-select 下拉列表中的多个选定项目。我没有指定任何 bindValue,因此项目应该由对象绑定(如https://www.npmjs.com/package/@ng-select/ng-select中指定)
但是,在尝试执行此操作时,不会根据对象而是根据显示的标签来选择项目。此外,仅选择第一个标签。
示例:app.component.html
<form [formGroup]="group">
<div class="form-group" formGroupName="school">
<ng-select labelForId="school" placeholder="Select school" [items]="schools" formControlName="code"
bindLabel="displayLabel" multiple="true" groupBy="city">
</ng-select>
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
应用程序组件.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
group: FormGroup;
schools = [];
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.initSchools();
const formModel = {
school: new FormGroup({
code: new FormControl(null, Validators.required) …Run Code Online (Sandbox Code Playgroud) multi-select angular-ngselect dropdown angular angular-reactive-forms
我有三个输入字段,即
因此,origin at值必须介于最低分数和最高分数之间。
我的表格看起来像这样
this.fb.group({
min: ['', [Validators.required]],
max: ['', [Validators.required]],
origin: ['', [Validators.required, Validators.min(?), Validators.max(?)]] # I need value of min and max input field value here
})
Run Code Online (Sandbox Code Playgroud)
如何正确验证来源输入字段?
编辑:
注意 -fb是FormBuilder
我的整个表格
this.scalesForm = this.fb.group({
scales: this.fb.array([
this.fb.group({
type: ['x', [Validators.required]],
name: ['', [Validators.required]],
components: this.fb.array([], [Validators.required]),
min: ['', [Validators.required]],
max: ['', [Validators.required]],
origin: ['', [Validators.required]]
}),
this.fb.group({
type: ['y', [Validators.required]],
name: ['', [Validators.required]],
components: this.fb.array([], [Validators.required]),
min: ['', [Validators.required]], …Run Code Online (Sandbox Code Playgroud) 问题:
我创建了一个formGroupusing formbuilder. FormGroup 有一个控件,其.名称中有。现在,当我尝试formControl使用formGroup.get方法时,它返回null。
代码
export class AppComponent implements OnInit {
name = 'Angular';
obj = {};
formGroup: FormGroup;
constructor(private formBuilder: FormBuilder) {
}
ngOnInit() {
this.obj["parent.child"] = new FormControl();
this.obj["parent"] = new FormControl();
this.formGroup = this.formBuilder.group(this.obj);
// All controls
console.log(this.formGroup.controls);
// This is the problem its not geting the form control if I have '.' in the name of form control.
console.log(this.formGroup.get("parent.child"));
// If I am getting …Run Code Online (Sandbox Code Playgroud) 我正在研究 Angular 10。已经 3 天了,我遇到了 Angular 模板驱动和反应式表单的问题。
我想做的:创建一个包含许多子组件的复杂表单(以便分离大量代码)。然后单击一个按钮,我想验证所有表单和子组件。我想以某种方式验证子组件。
我创建的内容:具有双向绑定的模板驱动表单,因为我相信它更容易并且对于我的情况来说不需要。
我已经设法使验证仅适用于基本表单。我无法在儿童组件上做到这一点。我看到很多关于这个问题的帖子并尝试了很多,但我很困惑。
我的代码:
mainForm.html
<div class="card m-3">
<div class="card-body">
<fieldset>
<form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
<div class="form-row">
<div class="form-group col">
<label>Title</label>
<select name="title" class="form-control" [(ngModel)]="model.title" #title="ngModel" [ngClass]="{ 'is-invalid': f.submitted && title.invalid }" required>
<option value=""></option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Ms">Ms</option>
</select>
<div *ngIf="f.submitted && title.invalid" class="invalid-feedback">
<div *ngIf="title.errors.required">Title is required</div>
</div>
</div>
<div class="form-group col-5">
<label>First Name</label>
<input type="text" name="firstName" class="form-control" [(ngModel)]="model.firstName" #firstName="ngModel" [ngClass]="{ 'is-invalid': …Run Code Online (Sandbox Code Playgroud) 我按照本指南创建ControlContainer可重用表单,成功创建了可重用表单组,但是当我尝试使用 创建可重用表单元素时matInput,遇到了No value accessor错误。这是my-form-field.ts文件:
import { Component, Input, OnInit } from '@angular/core';
import {
ControlContainer,
FormBuilder, FormControl,
FormGroup,
FormGroupDirective,
} from '@angular/forms';
@Component({
selector: 'my-form-field',
template: `
<mat-form-field>
<mat-label>{{label}}</mat-label>
<input matInput [formControlName]="formControlName">
</mat-form-field>
`,
viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }],
})
export class MyFormFieldComponent implements OnInit {
@Input() formControlName: string;
@Input() label: string;
formGroup: FormGroup;
constructor(private ctrlContainer: FormGroupDirective, private formBuilder: FormBuilder) {
}
ngOnInit(): void {
this.formGroup = this.ctrlContainer.form; …Run Code Online (Sandbox Code Playgroud) code-reuse angular-material angular angular-reactive-forms controlvalueaccessor
我有一个 Angular ReactiveForms FormArray,它基本上渲染一个带有文件输入的扩展面板。我想传递 FormArray 的 FormGroup 的索引,根据该索引选择文件。为此,我将索引 (bankAccountIndex) 作为附加参数传递给文件输入(更改)事件。但是,该值始终为零。如果我对标记中的值进行硬编码,那么我会在代码隐藏中获得该值,但在传递索引变量时不会获得该值。
下面是我的代码:
<mat-accordion [togglePosition]="'before'">
<ng-container *ngFor="let bankFormGroup of bankAccountsFormArray.controls; let bankAccountIndex=index">
<ng-container [formGroupName]="bankAccountIndex">
<mat-expansion-panel>
<span>
<label for="file-upload" class="override-margin-bottom" [ngClass]="{'disabled-control': form.disabled}">
<fa-icon [icon]="faUpload" class="file-upload-icon" size="lg"></fa-icon>
</label>
<input type="file" id="file-upload" (change)="onHandleBankLogoUploadEvent($event.target.files, bankAccountIndex)"
style="display: none;" />
<input type="text" #bankLogo formControlName="bankLogoBase64Image" style="display: none;">
<img [src]="bankLogo.value" *ngIf="bankLogo.value" style="height: 30px;" />
</span>
</mat-expansion-panel>
</ng-container>
</ng-container>
</mat-accordion>
Run Code Online (Sandbox Code Playgroud)
TypeScript 文件输入更改事件处理程序:
onHandleBankLogoUploadEvent(files: FileList, bankAccountIndex: number) {
...
}
Run Code Online (Sandbox Code Playgroud)
我的组件OnInit():
ngOnInit() {
this.toastrService.overlayContainer = this.toastContainer;
this.toastrService.clear();
this.initializeForm();
this.bankAccounts$ = this.firestore.collection<BankAccount>('bankAccounts')
.valueChanges({ …Run Code Online (Sandbox Code Playgroud) 我正在以这种方式使用父表单和子组件表单。/sf/answers/4151721101/
当父表单提交了按钮 Ng 时,如何让子组件知道?ParentForm 变量在子组件中作为变量。有没有办法,我可以将parentFormGroup 作为一个事件来告诉我?
当子窗体知道时,我想计算一些复杂的值(不在窗体中),并将它们发送到父组件。
父组件:
ngOnInit() {
this.parentForm = this.fb.group({
'customerName': [null, [Validators.required]],
'phoneNumber': [null, [Validators.required]],
})
<form [formGroup]="parentForm" (ngSubmit)="onSubmit()">
<app-child [form]="parentForm"></app-child>
<button type="submit">Purchase</button>
</form>
Run Code Online (Sandbox Code Playgroud)
子组件:
需要知道在这个组件中,parentForm 是什么时候提交的。
@Input() parentForm: FormGroup;
ngOnInit() {
this.parentForm.addControl('address', new FormControl(Validators.required));
this.parentForm.addControl('city', new FormControl(Validators.required));
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试验证Angular项目中的输入字段并使用教程,似乎它按预期工作。
上面使用反应式表单来完成验证工作,如下所示:
<form [formGroup]="angForm" novalidate>
<div class="form-group">
<label>Name:</label>
<input class="form-control" formControlName="name" type="text">
</div>
<div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['name'].errors.required">
Name is required.
</div>
</div>
<div class="form-group">
<label>Address:</label>
<input class="form-control" formControlName="address" type="text">
</div>
<div *ngIf="angForm.controls['address'].invalid && (angForm.controls['address'].dirty || angForm.controls['address'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['address'].errors.required">
email is required.
</div>
</div>
<button type="submit"
[disabled]="angForm.pristine || angForm.invalid" class="btn btn-success">
Save
</button>
</form>
Run Code Online (Sandbox Code Playgroud)
上面的按钮默认是禁用的。因此,当用户开始书写并将输入字段保留为空白时,它就会验证表单。我的要求是启用该按钮,单击时验证将起作用。所以我所做的如下:
<form [formGroup]="angForm" #addData='ngForm' (ngSubmit)="AddData(addData)">
<button type="submit" class="btn btn-success"> //Removed the disabled property …Run Code Online (Sandbox Code Playgroud) 我正在构建一个表单,可以选择为您的图标选择颜色
一切正常,唯一的问题是颜色选择器不会影响我的反应形式的值。我尝试了很多方法来构建第二个输入字段,强制它的值,然后使用它,getter 函数,并将其用作表单值。
color!: string;
get colorChange() {
let newColor:string;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return newColor = this.color
}
categoryForm!: FormGroup;
// eslint-disable-next-line @typescript-eslint/no-inferrable-types
isSubmitted: boolean = false;
constructor(private _fb: FormBuilder, private _categoriesService: CategoriesService, private toastr: ToastrService, private location: Location, private route:ActivatedRoute) { }
ngOnInit(): void {
this.categoryForm = this._fb.group({
name: ['', [Validators.required, Validators.minLength(6)]],
icon: ['', [Validators.required]],
color: [this.colorChange, [Validators.required]]
});
this._checkEditMode();
}Run Code Online (Sandbox Code Playgroud)
<div class="category">
<h1 class="h1"> {{title}}</h1>
<div class="card">
<form class="my-3 mx-3" [formGroup]="categoryForm" (ngSubmit)="onSubmit()">
<div class="mb-3">
<label for="exampleInputName" class="form-label">Category Name</label> …Run Code Online (Sandbox Code Playgroud)我知道这个问题以前被问过很多次。我想在提交后重置我的表单和验证。我使用 formGroup 创建一个表单。如果表单有效,我使用了一个按钮来提交表单,我使用 form.reset() 重置了表单,它清除了字段,但没有清除我也尝试使用的错误
this.form.markAsPristine();
this.form.markAsUntouched();
this.form.updateValueAndValidity();
Run Code Online (Sandbox Code Playgroud)
重置表单验证但它不起作用
从下面给出的代码中,我可以重置表单,但输入字段仍然脏或被触摸,结果输入字段标记为红色。有人可以建议我创建表单、重置表单和验证的最佳实践是什么。
我的html代码是
<mat-form-field class="example-full-width" appearance="outline" style="width: 100%;">
<input type="text" matInput formControlName="title" placeholder="Enter Module Title" #message maxlength="50">
<mat-error *ngIf="form.controls.title.hasError('required') && (form.controls.title.dirty || form.controls.title.touched)">
Module Title is <strong>required</strong>
</mat-error>
</mat-form-field>
<button (click)="save()"> Save</button>
Run Code Online (Sandbox Code Playgroud)
这是我的 .TS 文件
@ViewChild('my2Form', { static: false }) my2Form!: NgForm;
this.form = this.fb.group({
title: ['',[Validators.required]],
});
save()
{ if(this.form.invalid)
{ this.form.markAllAsTouched();
return;
}
else
{
this.my2Form.resetForm();
this.form.markAsPristine();
this.form.markAsUntouched();
this.form.updateValueAndValidity();
this.form.markAsPristine();
}
Run Code Online (Sandbox Code Playgroud)
angular ×10
typescript ×2
angular11 ×1
angular8 ×1
code-reuse ×1
dropdown ×1
formgroups ×1
forms ×1
mean-stack ×1
multi-select ×1
validation ×1