来自Angular2验证

时间:2016-10-10 14:46:56

标签: validation angular

您好我想知道是否可以在Angular2的表单组中创建if语句。

我想如果用户点击复选框,则应考虑输入字段测试(应该要求字段),否则不要。我怎么能意识到它?

Angular2档案

<input type="email" id="email" required="required">
<a id="link" href="some_external_link" target="_blank">Do the thing</a>

HTML文件

$("#link").on("click", function(event) {
  var email = $('#email')[0];
  if (!email.checkValidity()) {
    event.preventDefault();
  }
});

2 个答案:

答案 0 :(得分:0)

试试这个:

constructor(fb:FormBuilder){
    this.recordform = fb.group({
        name:['',Validators.required],
        test:['',Validators.required]
        }
    });
    this.recordform.controls.test.valueChanges
      .subscribe(value => {
         if(!value) 
           this.recordform.removeControl('test');
         else 
           this.recordform.addControl('test', new FormControl('test', Validators.required));
       });
}

答案 1 :(得分:0)

我会做这样的事情。以下是app.component.ts

print ((df1 == 1).values.any())
True
print ((df2 == 1).values.any())
True

将它们全部放入Form Control并将自定义验证器应用于Form Group的第二个参数。我还在类中创建了一个属性,用于复选框控件以在html中访问它。以下是app.component.html

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { CustomValidator } from './custom-validators';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [`./app.component.css`]
})
export class AppComponent implements OnInit {
  recordForm: FormGroup;
  checkbox: FormControl;
  constructor(private fb: FormBuilder) { }
  ngOnInit() {
    this.recordForm = this.fb.group({
      name: this.fb.control('', [Validators.required]),
      checkbox: this.fb.control(''),
      test: this.fb.control('')
    }, {
        validator: CustomValidator.checkCheckbox()
      });
    this.checkbox = this.recordForm.get('checkbox') as FormControl;
  } // End Of Init
} // End of Class

在测试控件标签上放置if语句,仅在复选框值为true时显示。以下是custom-validator.ts。

<div [formGroup]="recordForm">
  <label>Name: <input formControlName="name" type="text" ></label>
  <label>Checkbox: <input formControlName="checkbox" type="checkbox"></label>
  <label *ngIf="checkbox.value">Test: <input formControlName="test" type="text"></label>
</div>

在这种情况下,如果未选中复选框值,或者如果选中它并且测试值不为空,则该方法将返回null(有效),否则将返回一个为true的对象键(无效)。希望这可以帮助!