标签: angular-reactive-forms

Angular 2:在某些条件下应用Validator.required验证

我有一个有角度的2形式,其中我必须在某些条件下需要一个字段,如:

description:  ['', Validators.required]
Run Code Online (Sandbox Code Playgroud)

仅在某些类型的条件下才需要此描述字段,例如:

if(true){descReq = true};
Run Code Online (Sandbox Code Playgroud)

我怎么能做到这一点,请建议.提前致谢!

angular2-forms angular angular-reactive-forms angular-forms

6
推荐指数
2
解决办法
2059
查看次数

多个自定义验证器,其反应形式为角度2

我有两个自定义validator的reactive form,我叫下面的函数来创建组件构造函数形式:

private createForm(): void {
this.passwordUpdateForm = this.formBuilder.group({
    newpassword : [null, Validators.required],
    passwordconfirm: [null, Validators.required]
},
{
    validator: [PasswordValidation.PasswordMatch, PasswordValidation.PasswordRule] // validation method

});
Run Code Online (Sandbox Code Playgroud)

}

PasswordValidation是一个具有以下两个功能的类

    export class PasswordValidation {

     public  static PasswordMatch(control: AbstractControl) {
        let password = control.get('newpassword'); // to get value in input tag
        if(password){
            let confirmPassword = control.get('passwordconfirm').value; // to get value in input tag
            if (password.value !== confirmPassword) {
                control.get('passwordconfirm').setErrors({ ['passwordmatch'] : true});
            }else {
                return null;
            }
        }
    } …
Run Code Online (Sandbox Code Playgroud)

custom-validators angular-validation angular angular-reactive-forms angular-forms

6
推荐指数
1
解决办法
6199
查看次数

将formControlName用于反应形式的自定义输入组件

有一个自定义的输入组件,它以反应形式用于验证:

@Component({
    moduleId: module.id.toString(),
    selector: 'custom-select',
    templateUrl: 'custom-select.component.html',
    styleUrls: ['custom-select.component.css']
})
export class CustomSelectComponent {
    @Input() public items: SelectModel[];
    public model: SelectModel;
    constructor(private customSelectService: CustomSelectService) {
        this.customSelectService.Selected.subscribe((data: SelectModel) => {
            this.model = data;
        });
    }
    public newSelect(select: SelectModel): void {
        this.customSelectService.updateSelected(select);
    }
}
Run Code Online (Sandbox Code Playgroud)

效果很好,我正在custom-select以反应形式使用,并希望按如下所示进行验证:

<custom-select id="country" [items]="selectItems" formControlName="country"></custom-select>
<div *ngIf=" myFrom.controls['country'].invalid && (myFrom.controls['country'].dirty 
             || myFrom.controls['country'].touched) " class="ha-control-alert">
    <div *ngIf="myFrom.controls['country'].hasError('required')">Country is required</div>
</div>
Run Code Online (Sandbox Code Playgroud)

这就是我在组件中声明表格的方式

this.myFrom = this.formBuilder.group({
    country: [null, Validators.required],
})
Run Code Online (Sandbox Code Playgroud)

但是当我添加formControlName验证时,会出现错误,提示名称为'country'的表单控件没有值访问器。我该如何处理?

angular-validation angular angular-reactive-forms angular-forms

6
推荐指数
1
解决办法
5381
查看次数

Reactive Forms双向绑定错误:无法分配给只读属性

我试图通过以下代码实现双向绑定:

export interface User {
  name: string;
  subscribed: boolean;
}

export class UserEditComponent implements OnInit {
  modifiedUser: User;
  userForm: FormGroup;

  ngOnInit() {
    this.userForm = this.fb.group({
      name: ['', Validators.required],
      subscribed: false
    });

    this.route.paramMap.switchMap((params: ParamMap) => {
      return this.userService.getUser(params.get('id'));
    }).subscribe((user) => {
      this.modifiedUser = user;
      this.userForm.setValue({
        name: this.modifiedUser.name,
        subscribed: this.modifiedUser.subscribed
      });
    });

    this.userForm.valueChanges.subscribe((data) => {
      this.modifiedUser.subscribed = data.subscribed;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)
<form [formGroup]="userForm">
  <textarea class="form-control" formControlName="name">{{modifiedUser.name}}</textarea>
  <input type="checkbox" class="custom-control-input" formControlName="subscribed">
</form>
Run Code Online (Sandbox Code Playgroud)

但是,TypeError: Cannot assign to read only property 'subscribed' of object …

angular angular-reactive-forms

6
推荐指数
1
解决办法
793
查看次数

_this.form.get不是angular4中的函数

我开发一个角度4应用程序,并在将数据绑定到表单时遇到问题.绑定代码似乎很好,不知道问题是什么.当我调试应用程序时,我可以看到结果正确填充了下面的代码行this.editMovieForm = result; 在setFormValues()方法中.当我检查控制台窗口时,我看到以下错误

EditmovieComponent.html:1 ERROR TypeError: _this.form.get is not a function
    at forms.es5.js:4907
    at Array.forEach (<anonymous>)
    at FormGroupDirective.webpackJsonp.../../../forms/@angular/forms.es5.js.FormGroupDirective._updateDomValue (forms.es5.js:4906)
    at FormGroupDirective.webpackJsonp.../../../forms/@angular/forms.es5.js.FormGroupDirective.ngOnChanges (forms.es5.js:4774)
    at checkAndUpdateDirectiveInline (core.es5.js:10840)
    at checkAndUpdateNodeInline (core.es5.js:12341)
    at checkAndUpdateNode (core.es5.js:12284)
    at debugCheckAndUpdateNode (core.es5.js:13141)
    at debugCheckDirectivesFn (core.es5.js:13082)
    at Object.eval [as updateDirectives] (EditmovieComponent.html:1)


ERROR Error: Uncaught (in promise): TypeError: _this.editMovieForm.patchValue is not a function
TypeError: _this.editMovieForm.patchValue is not a function
    at main.bundle.js:446
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (polyfills.bundle.js:2908)
    at Object.onInvoke (vendor.bundle.js:146628)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (polyfills.bundle.js:2907)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.run (polyfills.bundle.js:2658)
    at polyfills.bundle.js:3389
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (polyfills.bundle.js:2941)
    at …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms angular4-forms

6
推荐指数
1
解决办法
7746
查看次数

Angular 5 + Angular Material Select + Reactive Forms ==不显示初始选项

正如标题所说,我有一个包含多个<mat-select>内容的反应形式.在初始表单加载时,即使form.value显示初始选项,也不会显示初始选项.

相关组件:

export class DesJobInfoEditComponent implements OnInit {

...

currentJobData: IJob;
jobTypes: IJobType[];

...

constructor(private fb: FormBuilder) {

    ...

        // Construct forms
        this.createForm();

        this.initializeForm();

}

createForm() {
    this.editJobInfoForm = this.fb.group({
        ...
        JobType: '', // mat-select
        ...
    });
}

initializeForm() {
    this.rebuildForm();
}

rebuildForm() {
    this.editJobInfoForm.reset({
        ...
        JobType: this.jobTypes[this.currentJobData.JobType].DisplayDesc,
        ...
    });
}
Run Code Online (Sandbox Code Playgroud)

}

相关的HTML:

<mat-form-field fxFlex>
      <mat-label>Job Type</mat-label>
       <mat-select formControlName="JobType" placeholder="Job Type">
              <mat-option *ngFor="let jobType of jobTypes" value="jobType.value">
                     {{ jobType.DisplayDesc }}
               </mat-option>
        </mat-select>
  </mat-form-field>
Run Code Online (Sandbox Code Playgroud)

加载表单时,选择不显示最初选择的选项,但是,它们设置正确,显然:

Form value …
Run Code Online (Sandbox Code Playgroud)

angular-material angular angular-reactive-forms

6
推荐指数
2
解决办法
9894
查看次数

角度反应形式设置和清除验证器

请协助,我想删除表格中的所有验证人,请告知是否可能,如果您有表格组20或更多表单控件,如果不是更好的方法删除验证器,请参阅下面的示例.

 ngOnInit() {
    this.exampleFormGroup = this.formBuilder.group({
     surname: ['', [Validators.required, Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]],
     initials: ['', [Validators.required, Validators.maxLength(4)]]
     });
  }

 public removeValidators() {
    this.exampleFormGroup.get('surname').clearValidators();
    this.exampleFormGroup.get('initials').clearValidators();
    this.exampleFormGroup.updateValueAndValidity();
 }

 public addValidators() { 
  this.exampleFormGroup .get('surname').setValidators([Validators.required,Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]);
  this.exampleFormGroup.get('initials').setValidators([Validators.required, Validators.maxLength(4)]);
  this.exampleFormGroup.updateValueAndValidity(); 
 }
Run Code Online (Sandbox Code Playgroud)

上面的方法addValidators()将添加验证器,并removeValidators()在执行时删除验证器.但我遇到的问题是,我必须指定表单控件我试图清除验证器.有没有办法this.exampleFormGroup.clearValidators();在表单中完成并清除所有内容并再次this.exampleFormGroup.setValidators()将其设置回来.我知道我可能会要求一个独角兽,但在formGroup有20个或更多控件的情况下,清除和设置验证器可能会很痛苦,因此非常感谢如何处理这些场景的地图.

angular angular-reactive-forms

6
推荐指数
1
解决办法
1万
查看次数

ANGULAR 6:错误TS2315:类型'ModuleWithProviders'不是通用的

您好我遇到了一个与任何事情无关的问题.

我展示了一些我的代码,希望它可以有用.

考虑到一旦我开始创建一个Reactive Form就出现了这个问题.

首先,这是我的package.json:

{
  "name": "name",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.0.3",
    "@angular/common": "^6.0.3",
    "@angular/compiler": "^6.0.3",
    "@angular/core": "^6.0.3",
    "@angular/forms": "^6.1.2",
    "@angular/http": "^6.0.3",
    "@angular/platform-browser": "^6.0.3",
    "@angular/platform-browser-dynamic": "^6.0.3",
    "@angular/router": "^6.0.3",
    "@ng-bootstrap/ng-bootstrap": "^2.2.0",
    "core-js": "^2.5.4",
    "rxjs": "^6.0.0",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular/compiler-cli": "^6.0.3",
    "@angular-devkit/build-angular": "~0.6.8",
    "typescript": "~2.7.2",
    "@angular/cli": "~6.0.8",
    "@angular/language-service": "^6.0.3",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-reactive-forms

6
推荐指数
1
解决办法
9602
查看次数

为什么在Jasmine Angular单元测试中不触发反应形式控件的更改事件?

我有一个更改函数,该函数将传递给反应形式控件的更改事件的更改事件,该控件评估脏状态并检查控件上是否有任何错误,如果是,则将布尔标志设置为true / false。然后,此布尔标志用于确定是否显示<div>具有错误消息的元素。这在浏览器中可以正常工作,但是在运行单元测试时,永远不会将“ dirty”设置为true。这是我的代码:

的HTML

<form [formGroup]="myForm" novalidate>
    <input id="age" formControlName="age" (change)="onChange()" />
    <div id="ageError" *ngIf="ageIsError()">
        <label>Age has errored</label>
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

零件

constructor(private fb: FormBuilder) {}

ngOnInit() {
    this.myForm = this.fb.group({
        age: [null, [Validators.min(18)]]
    });
}

onChange() {
    if (this.ageIsError())
        // do something
}

ageIsError() {
    return this.myForm.controls.age.hasError('min') &&
           this.myForm.controls.age.dirty;
}
Run Code Online (Sandbox Code Playgroud)

单元测试

it('should show error message when age is less than 18', fakeAsync(() => {
    let age = component.myForm.controls.age;
    age.setValue('10', { emitEvent: …
Run Code Online (Sandbox Code Playgroud)

unit-testing jasmine typescript angular angular-reactive-forms

6
推荐指数
1
解决办法
1262
查看次数

使用FormBuilder创建禁用的表单组

假设我们有myFormGroup通过FormBuilder初始化的:

this.myFormGroup = this.fb.group(
  {
    field1: ['', SomeValidator1],
    field2: ['', AnotherValidator2],
    field3: [''],
    ...
  }
);
Run Code Online (Sandbox Code Playgroud)

我知道我们可以禁用特定的表单控件,例如:

fb.control({value: 'my val', disabled: true});
Run Code Online (Sandbox Code Playgroud)

当然,我可以在示例中使用此语法,并将组中的每个控件标记为已禁用。但是表单组可能有很多控件。

因此,问题-是否有任何方法可以在通过FormBuilder 创建(而不是之后)禁用整个FormGroup / FormArray的同时?

ps我问这个问题的原因是因为我需要有条件地初始化具有不同类型用户权限的活动或禁用字段的表单组。

angular angular-reactive-forms angular-forms

6
推荐指数
2
解决办法
2303
查看次数