我正在使用带反应形式的Angular 4.我有一个表单数组,我试图绑定到我在组件中跟踪的数组.我正在使用反应式表单,所以我可以进行验证,所以我不想使用模板表单方法.
我将项添加到表单数组中,如下所示:
createFormWithModel() {
this.orderForm = this.fb.group({
orderNumber: [this.order.ProductBookingOrder],
orderDate: [this.order.PurchaseOrderIssuedDate],
lineDetailsArray: this.fb.array([])
})
const arrayControl = <FormArray>this.orderForm.controls['lineDetailsArray'];
this.order.ProductBookingDetails.forEach(item => {
let newGroup = this.fb.group({
ProductName: [item.ProductName],
Quantity: [item.ProductQuantity.Quantity],
UOM: [item.ProductQuantity.UOM],
RequestedShipDate: [item.RequestedShipDate]
})
})
}
Run Code Online (Sandbox Code Playgroud)
orderForm显然是我的反应形式FormGroup.订单是我从API获取的对象,我想更新其值,包括行详细信息.我想我应该在每个newGroup上使用'valueChanges.subscribe',但我不知道如何获得已更改的项的索引.有什么想法吗?
newGroup.valueChanges.subscribe('i want value and index some how' => {
this.order.ProductbookingDetails[index].ProductName = value.ProductName;
});
Run Code Online (Sandbox Code Playgroud)
这是此部分的HTML:
<tbody formArrayName="lineDetailsArray">
<tr [formGroupName]="i" *ngFor="let line of orderForm.controls['lineDetailsArray'].controls; index as i">
<td><input class="form-control" type="text" placeholder="Product Name" formControlName="ProductName" required/></td>
<td><input class="form-control" type="number" step=".01" (focus)="$event.target.select()" placeholder="Quantity" formControlName="Quantity"/></td>
<td><input class="form-control" readonly …Run Code Online (Sandbox Code Playgroud) 我有一个反应式表单,并根据fooRequired我想要将字段设置为必填或非必填的属性。
我无法更改它,因为它是初始设置的。那我能做什么呢?
fooRequired = false;
form = new FormGroup({
foo: new FormControl(null, [Validators.required])
});
toggle() { this.fooRequired = !this.fooRequired; }
Run Code Online (Sandbox Code Playgroud) 有没有办法在使用Reactive表单时以角度禁用整个表单.我知道可以逐个禁用它们.
this.tempForm = this.fb.group({
m26_type: '',
m26_name: ''
})
this.tempForm.get('m26_type').disable();
Run Code Online (Sandbox Code Playgroud)
是否可以禁用整个表单而不是单独禁用每个控制器?
typescript angular2-formbuilder angular angular-reactive-forms
我正在使用Angular v4.4.4.在组件中,在模板中单击按钮后,假定反应形式有效,将保存表单.像(伪代码)的东西:
public onSave(): void {
if (this.myForm.valid) {
this._createFoo();
}
}
private _createFoo(): void {
this._fooService.createItem(this.foo).subscribe(result => {
// stuff happens...
});
}
Run Code Online (Sandbox Code Playgroud)
在相关的单元测试中,我需要强制表单有效,以便我可以确认正在调用服务.像这样的东西:
it('should create Foo', () => {
const spy = spyOn(_fooService, 'createItem').and.callThrough();
component.foo = new Foo();
fixture.detectChanges();
const bookButton = fixture.debugElement.query(By.css('#bookButton'));
expect(bookButton !== null).toBeTruthy('missing Book button');
bookButton.triggerEventHandler('click', null);
expect(spy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
这将失败,因为myForm永远不会设置为有效.
在这种特殊情况下,我不想给表单中的每个输入赋值.我只需要观察并查看服务订阅是否发生.如何强制表格有效?
我正在使用带有Reactive表单的Angular 5,并且需要使用valueChanges来动态地禁用所需的验证
组件类:
export class UserEditor implements OnInit {
public userForm: FormGroup;
userName: FormControl;
firstName: FormControl;
lastName: FormControl;
email: FormControl;
loginTypeId: FormControl;
password: FormControl;
confirmPassword: FormControl;
...
ngOnInit() {
this.createFormControls();
this.createForm();
this.userForm.get('loginTypeId').valueChanges.subscribe(
(loginTypeId: string) => {
console.log("log this!");
if (loginTypeId === "1") {
console.log("disable validators");
Validators.pattern('^[0-9]{5}(?:-[0-9]{4})?$')]);
this.userForm.get('password').setValidators([]);
this.userForm.get('confirmPassword').setValidators([]);
} else if (loginTypeId === '2') {
console.log("enable validators");
this.userForm.get('password').setValidators([Validators.required, Validators.minLength(8)]);
this.userForm.get('confirmPassword').setValidators([Validators.required, Validators.minLength(8)]);
}
this.userForm.get('loginTypeId').updateValueAndValidity();
}
)
}
createFormControls() {
this.userName = new FormControl('', [
Validators.required,
Validators.minLength(4)
]);
this.firstName = new FormControl('', …Run Code Online (Sandbox Code Playgroud) 我是 Angular 新手,我使用版本 11。并且我的 html 文件中的 formGroup 属性有问题。
错误 :
'表格组| null' 不可分配给类型'FormGroup'。类型“null”不可分配给类型“FormGroup”。
2 <form [formGroup]="produitFormGroup">
我的html代码。
<form [formGroup]="produitFormGroup">
<div class="form-group">
<label>Nom</label>
<input type="text" class="form-control" formControlName="name">
</div>
<div class="form-group">
<label>Prix</label>
<input type="text" class="form-control" formControlName="price">
</div>
<div class="form-group">
<label>Quantite</label>
<input type="text" class="form-control" formControlName="quantity">
</div>
<div class="form-group">
<label>Selected</label>
<input type="checkbox" formControlName="selected">
</div>
<div class="form-group">
<label>Available</label>
<input type="checkbox" formControlName="available">
</div>
<button class="btn btn-success">Enregistrer</button>
</form>
Run Code Online (Sandbox Code Playgroud)
我的 ts 文件代码:
produitFormGroup: FormGroup | null= null;
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.produitFormGroup = this.fb.group({ …Run Code Online (Sandbox Code Playgroud) 无法以与Angular文档相同的方式访问它,因此必须首先获取FormGroup实例并在那里找到FormControl实例.我想知道为什么?这个例子有效:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
name="username"
class="form-control"
formControlName="username"
>
<div *ngIf="myForm.controls.username.invalid" class="alert alert-danger">
username is required
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
虽然这会引发错误(仅在*ngIf语句中这些差异):
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
name="username"
class="form-control"
formControlName="username"
>
<div *ngIf="username.invalid" class="alert alert-danger">
username is required
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
无法读取未定义的属性"无效"
form.component:
import {Component} from '@angular/core';
import {FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'sign-up',
templateUrl: 'app/sign-up.component.html'
})
export class SignUpComponent {
myForm = new FormGroup({
username: new FormControl('username', Validators.required),
password: new FormControl('', Validators.required), …Run Code Online (Sandbox Code Playgroud) 我有一个充满实例的FormGroup控件FormArrayFormGroup
someForm = this.fb.group({
days: this.fb.array([
this.fb.group({
description: ['']
})
])
})
Run Code Online (Sandbox Code Playgroud)
另外,我有一个用于该数组的吸气剂
get days(): FormArray {
return this.someForm.get('days') as FormArray;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试迭代FormArray并将其分配给[formGroup]指令时,如本文所示
<div *ngFor="let day of days.controls">
<ng-container [formGroup]="day">
...
Run Code Online (Sandbox Code Playgroud)
我越来越
error TS2740: Type 'AbstractControl' is missing the following properties from type 'FormGroup': controls, registerControl, addControl, removeControl, and 3 more.
Run Code Online (Sandbox Code Playgroud) 我有一个Angular7 app&Reactive Forms Module用于验证和表单。
这就是我的模板的样子。
<div class="row" [formGroup]="jobForm">
<div class="form-group"
[ngClass]="{'has-error': jobForm.get('jobTitle').errors &&
(jobForm.get('jobTitle').touched || jobForm.get('jobTitle').dirty) }">
<input type="text" class="form-control" formControlName="jobTitle" />
<span class="help-block" *ngIf="formError">
{{ formError.jobTitle }}
</span>
</div>
<br />
<button type="button" class="btn btn-primary" disabled="jobTitle.errors.required"
(click)="submit(jobTitle,jobDesc)">Create</button>
Run Code Online (Sandbox Code Playgroud)
组件.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
@Component({
selector: 'app-create-job',
templateUrl: './create-job.component.html',
styleUrls: ['./create-job.component.css']
})
export class CreateJobComponent implements OnInit {
constructor(private fb: FormBuilder) {}
jobForm: FormGroup;
formError: any; …Run Code Online (Sandbox Code Playgroud) 在成角度6之前,我曾[(ngModel)]用来直接将表单字段绑定到模型。现在不推荐使用(不能用于反应式表单),而且我不确定如何用表单值更新模型。我可以使用,form.getRawValue()但是这需要我用新的rawValue替换当前模型-这是不利的,因为我的主模型比本地表单模型更大并且具有更多的字段。
有任何想法吗?
angular ×10
typescript ×4
angular5 ×1
angular7 ×1
api ×1
formarray ×1
html ×1
javascript ×1
unit-testing ×1