我正在我的 Angular 9 应用程序中实现原子设计。这意味着我将用原子、分子和有机体来构建我的页面。除了 ReactiveFormsModule 之外,一切都很顺利。
我想将 转换<input />为它自己的组件,这样我就不必一直复制关联的 HTML。然而,反应形式却没有这些。
下面的示例在加载时返回错误:ERROR Error: No value accessor for form control with name: 'field2'
我用完整的代码制作了一个StackBlitz示例。
应用程序组件.ts
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({selector: 'app-root',templateUrl: './app.component.html'})
export class AppComponent {
form: FormGroup;
constructor(fb: FormBuilder) {
this.form = fb.group({
field1: ['value1', [Validators.required]],
field2: ['value2', [Validators.required]],
});
}
onSubmit() {console.log(this.form.value);}
}
Run Code Online (Sandbox Code Playgroud)
app.component.html这里我尝试用原子替换第二个输入。
import { Component } from '@angular/core';
import { FormGroup, …Run Code Online (Sandbox Code Playgroud) 我尝试使用反应式表单,我只需要为每个填充的项目创建键但是因为创建的第一个时刻,如果字段未满,它会发送 null 而我想要一个不为空的字段我发送的所有代码是:
form: FormGroup;
constructor() {
this.form = new FormGroup({
basePrice: new FormControl(null, [customeValidator.numberOnly()]),
discountValue: new FormControl(null, [customeValidator.numberOnly()]),
roomViewCount: new FormControl(null, [customeValidator.numberOnly()])
});
}
onCalcute() {
console.log(this.form.value);
if (this.form.valid) {
this.roomData = {
basePrice: this.form.value.basePrice,
discountValue: this.form.value.discountValue,
roomViewCount: this.form.value.roomViewCount
};
this.clicked = true;
}
}
Run Code Online (Sandbox Code Playgroud)
如果其中只有一个已满 console.log 返回
{
basePrice: 20,
discountValue: null,
roomViewCount: null
}
Run Code Online (Sandbox Code Playgroud)
但是我需要:
{
basePrice: 20
}
Run Code Online (Sandbox Code Playgroud) this.form = this.fb.array([
this.fb.group({
username: [null, Validators.required]
}),
this.fb.group({
username: [null, Validators.required]
}),
...
], uniqueUsernameValidator)
const uniqueUsernameValidator = control => {
// find duplicate
// when flagging the error
control.get('0.username').setErrors(ifThereIsAnError) // where `ifThereIsAnError` could be null
}
Run Code Online (Sandbox Code Playgroud)
以某种方式uniqueUsernameValidator静默required子表单字段指定的验证。如何解决这个问题呢?
validation angular-validation angular angular-reactive-forms angular-forms
目前我正在开发一个使用 Angular 5 和 primeng 的项目。我正在尝试以反应形式将来自下拉列表的国家/地区附加到电话号码中。当我从下拉列表中选择国家/地区代码时遇到问题它不会附加到我必须传递该值的电话号码。
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
profileForm = new FormGroup({
phoneNumber: new FormControl('')
})
onSubmit(phoneValue){
console.log(phoneValue)
}
onCountryChange(event){
console.log(event);
}
}
Run Code Online (Sandbox Code Playgroud)
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
profileForm = new FormGroup({
phoneNumber: new FormControl('')
})
onSubmit(phoneValue){ …Run Code Online (Sandbox Code Playgroud) 我已经实现了一个 stackblitz,您可以在其中使用某些配置创建动态表单。一切正常,直到您使用FormArray. 有什么想法吗?基本上,您的配置文件中可以有许多不同类型的字段。例如checkbox,等等text。number select在某些情况下,您应该有更复杂的结构,因此您应该有一个FormArray. 在这个 stackblitz 中,我试图代表正在发生的事情
因此,当我找到一个array类型时,我将创建一个 FormArray 而不是一个简单的FormControl字段列表
public fields: any[] = [
{
type: "text",
name: "firstName",
label: "First Name",
required: true
},
{
type: "text",
name: "lastName",
label: "Last Name",
required: true
},
{
type: "text",
name: "email",
label: "Email",
required: true
},
{
type: "text",
name: "description",
label: "Description",
required: true,
multiLine: true
},
{
type: "dropdown",
name: "country",
label: …Run Code Online (Sandbox Code Playgroud) typescript form-control angular angular-reactive-forms formarray
我试图弄清楚如何实现setDisabledState作为接口一部分的函数ControlValueAccessor,但我无法弄清楚如何从组件本身的外部实际触发该函数。
在我有的组件内
control = new FormControl();
setDisabledState(isDisabled: boolean): void {
this._renderer.setProperty(this.formField.nativeElement, 'disabled', isDisabled);
}
Run Code Online (Sandbox Code Playgroud)
如果我在组件的 NgOnInit 中执行以下操作,这会将我的禁用样式设置得很好。但我希望能够通过属性绑定来控制组件的禁用状态。
this.tenantListFormControl.disable();
Run Code Online (Sandbox Code Playgroud)
然而,实际上没有任何东西触发该函数。
我试过了
<app-custom-control [attr.disabled]="true"></app-custom-control>
<app-custom-control disabled></app-custom-control>
<app-custom-control [disabled]="true"></app-custom-control>
Run Code Online (Sandbox Code Playgroud)
最后一个甚至无效,因为“任何适用的指令等均未提供禁用的属性...”,因为我没有@Input()在组件上的任何位置禁用。无论如何这都没有帮助,因为一旦我设置了它,我应该如何处理它,我无法订阅它并以这种方式触发 setDisabledState 函数,因为它不是可观察的。
我如何实际触发此功能并禁用我的组件?
我是 angular8,我在表单组内有一个表单数组,但我想检测某个输入的新更改。
ngOnInit(): void {
this.makeForm = this.fb.group({
year:['', Validators.required],
amount:['', Validators.required],
desc:['', Validators.required],
details: new FormArray([
this.det(),
])
})
det(){
return new FormGroup({
requestfor : new FormControl(''),
remarks : new FormControl('')
})}
Run Code Online (Sandbox Code Playgroud)
我必须检查 formarray 值中每个值发生变化的数据。但如果我使用,我会收到错误
this.makeForm.value.details.get('requestfor').valueChanges
Run Code Online (Sandbox Code Playgroud)
错误是
ERROR TypeError: Cannot read property 'valueChanges' of undefined
Run Code Online (Sandbox Code Playgroud)
如何获取表单数组值内的值
如何获取该值......
angular angular-reactive-forms angular-forms angular-formbuilder angular8
如何对(Jest此处)自定义验证器进行单元测试,其中有FormGroup?我见过这个问题,但它是关于FormControl.
要测试的功能。
import { FormGroup } from '@angular/forms';
/**
* @description Validate if passwords are different.
* @function validatePasswords
* @param {string} passwordControlName - reference to formControlPassword of the contactForm.
* @param {string} confirmPasswordControlName - reference to formControlConfirmPassword of the contactForm.
* @returns {(formGroup: FormGroup) => void}
*/
export function validatePasswords(
passwordControlName: string,
confirmPasswordControlName: string
): (formGroup: FormGroup) => void {
return (formGroup: FormGroup) => {
// Get values of desired controls …Run Code Online (Sandbox Code Playgroud) unit-testing jestjs angular angular-reactive-forms angular-custom-validators
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-user-register',
templateUrl: './user-register.component.html',
styleUrls: ['./user-register.component.css']
})
export class UserRegisterComponent implements OnInit {
registerationForm: FormGroup = new FormGroup({});
constructor() { }
ngOnInit() {
this.registerationForm = new FormGroup({
userName : new FormControl(null, Validators.required),
email : new FormControl(null, [Validators.required, Validators.email]),
password : new FormControl(null, [Validators.required, Validators.minLength(8)]),
confirmPassword : new FormControl(null, [Validators.required]),
mobile : new FormControl(null, [Validators.required, Validators.minLength(10)])
}, this.passwordMatchingValidatior);
}
passwordMatchingValidatior(fg: FormGroup): Validators{
return this.registerationForm.get('password').value === …Run Code Online (Sandbox Code Playgroud) 我正在使用角度和故事书。我的模型中有 FormGroup 和 FormArray,但它们不适用于故事书。
a.stories.ts ->
import { CommonModule } from '@angular/common';
import { FormArray, FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Meta, moduleMetadata, Story } from '@storybook/angular';
export default {
title: 'Example/A',
component: AComponent,
decorators: [
moduleMetadata({
imports: [
CommonModule,
ReactiveFormsModule,
],
providers: [],
}),
],
} as Meta;
const Template: Story<AComponent> = (args: AComponent) => ({
props: args,
});
export const Costs = Template.bind({});
Costs.args = {
model: {
questions: [
{
...,
"question": "lorem ipsum", …Run Code Online (Sandbox Code Playgroud) angular ×10
angular5 ×1
angular8 ×1
form-control ×1
formarray ×1
jestjs ×1
ngxs ×1
primeng ×1
storybook ×1
typescript ×1
unit-testing ×1
validation ×1