Angular Form

Angular Form 学习笔记

Template Driven Form

  • Naming control elements

When you use [(ngModel)] on an element, you must define a name attribute for that element. Angular uses the assigned name to register the element with the [NgForm] directive attached to the parent

element.

[ngModel] is one-way binding, use it when you assign model.
[(ngModel)] is two-way binding, use it when you assign model and also listen the users' event.
ngModel: No binding, just register the control.

以上都可以结合name在TD表单中使用

To get access to the [NgForm] and the overall form status, declare a template reference variable.


      
       

Two ways to access form:

  1. Assign the local reference of your form to a function.
    OnSubmit(f)
    --
  2. Use @ViewChild()
    @ViewChild('f') myForm
    onSubmit(form: NgForm){
    console.log(this.myForm);
    }

给表单整体赋值:

// this.ValueToAssign in an object
this.myForm.setValue(this.valueToAssign);

给部分表单赋值:

this.myForm.form.patchValue(anotherObj);
  • Track Control States
State Class if true Class if false
The control has been visited. ng-touched ng-untouched
The control's value has changed. ng-dirty ng-pristine
The control's value is valid. ng-valid ng-invalid
  • Check Validation
  1. require -- 输入不能为空
    当输入不满足valid条件时, 通过 *ngIf 显示中的内容
//HTML


Please Enter a Valid Name.

//CSS
select.ng-invalid.ng-touched, input.ng-invalid.ng-touched{
  border: 1px solid red;
}
  1. 处理输入数字范围时,min, max 对于手动输入不起作用。可以使用 pattern=‘regular express’ 控制输入范围。

Reactive From

Form is created programmatically and synchronized with the DOM.

  • Import
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule
  ],
})
export class AppModule { }


  • Create Form
ngOnInit(): void {
    this.signupForm = new FormGroup({
      userData: new FormGroup({
        username: new FormControl(''),
        email: new FormControl('')
      }),
      gender: new FormControl('male'), 
    });
}

通过创建FormGroup来初始化Form的结构。FormGroup可以嵌套FormGroup。对应的HTML代码:

效果图

How to synchronize the code with the HTML template?

  • [formGroup] = "myForm" --- 捆绑表单
  • formGroupName = “userData” --- 捆绑group
  • formControlName = “userName” ---捆绑单个组件(需要逐个绑定)
  • formArrayName = “hobbies” --- 捆绑表单数组


  • Validation check
 forbiddenNames = ['skyler', 'ke'];
//built-in validator and custom validator
username: new FormControl('', [Validators.required, this.forbiddenName.bind(this)])

forbiddenName(c: FormControl): {[s: string]: boolean} {
    if (this.forbiddenNames.indexOf(c.value.toLowerCase()) !== -1){
      return { nameIsForbidden: true};
    }
    return null;
  }

The HTML code:


      
       
              This field is required!
              This name is invalid!
        

For custom validator, you will have to return a key-value pair. If validation check success, return { key: true }, else, return null or omit it.
Do not return { key: false }

Do not forget to bind(this) when use our custom validator, because we won't call it from the class. Angular will call it when check the validation.

We can also create async validator.
需要返回promise,或者observable

forbiddenEmail(c: FormControl): Observable| Promise {
    const promise = new Promise((resolve, reject) => {
      setTimeout(() => {
        if (c.value === '[email protected]'){
            resolve({emailIsForbidden : true});
          }else {
            resolve(null);
          }
        }, 1500
      );
    });
    return promise;
  }
  • 表单赋值
// set value to the form
    this.signupForm.setValue({
      userData: {
        username: 'Skyler',
        email: '[email protected]'
      },
      gender: 'female',
      hobbies: []
    });

    // Or use patch() to partial assign value to form

你可能感兴趣的:(Angular Form)