今天继续学习angular4表单部分的响应式表单,上次学习的模板式表单我们说过,它适用于一些规则简单的表单,那今天的响应式表单则是我们经常使用的一种表单规则。

PS:如果还没有之前的代码,请移步https://github.com/Dan2Lin/angular-form-demo.git去下载代码。

接下来一步步创建一个响应式模板:

(1)创建一个组件 ng g component reactiveForm.

(2)按照正常的方法我们写一个html表单

(3)在.ts文件中声明formModel,用来管理整个表单的后台容器

export class ReactiveFormComponent implements OnInit {
  formModel: FormGroup;
  model = {
    'hobbys': ['唱歌','跳舞','读书']
  }
  constructor(fb:FormBuilder) {
     this.formModel = fb.group({
         username:['Jetty', [Validators.required,Validators.minLength(6)]],
         mobile:['13244540000', mobileValidator],
         hobby:['-请选择-'],
         passwords:fb.group({
           password: ['123456',Validators.minLength(6)],
           confirmPass:['123456']
         },{
           validator:equalValidator
         })
     });
  }

  ngOnInit() {
  }

  onSubmit() {
    console.log("onSubmit reactive");
    if(this.formModel.valid) {
      console.log(this.formModel.value);
    }
  }

}
(4)修改html表单,添加上ng指令等

<form class="form" [formGroup] = "formModel" (submit) = "onSubmit()">
  <div class="form-control">
    <label for="username">用户名:</label>
    <input type="text" name="username" id="username" formControlName="username"/>
  </div>
  <div [hidden] = "formModel.get('username').valid">
    <div class="form-validate" [hidden]="!formModel.hasError('required','username')">用户名不能为空</div>
    <div class="form-validate" [hidden]="!formModel.hasError('minlength','username')">用户名长度不少于6位</div>
  </div>
  <div class="form-control height68" formGroupName="passwords">
    <div>
      <label for="password">密码:</label>
      <input type="password" name="password" id="password" formControlName="password">
    </div>
    <div class="form-validate" [hidden]="!formModel.hasError('minlength',['passwords','password'])">
       密码长度不低于6位
    </div>
    <div>
      <label for="confirmPass">确认密码:</label>
      <input type="password" name="confirmPass" id="confirmPass" formControlName="confirmPass"/>
    </div>
  </div>
  <div class="form-validate" [hidden]="!formModel.hasError('equal','passwords')">
    {{formModel.getError('equal','passwords')?.desc}}
  </div>
  <div class="form-control">
    <label for="mobile">电话:</label>
    <input type="text" name="mobile" id="mobile" formControlName="mobile"/>
  </div>
  <div [hidden]="formModel.get('mobile').valid || formModel.get('mobile').untouched">
     <div [hidden]="!formModel.hasError('mobile','mobile')">请输入正确的电话格式</div>
  </div>
  <div class="form-control">
    <label for="hobby">爱好:</label>
    <select name="hobby" id="hobby" formControlName="hobby">
      <option value="-请选择-" disabled>-请选择-</option>
      <option *ngFor="let hobby of model.hobbys" [value]='hobby'>{{hobby}}</option>
    </select>
  </div>
  <div><input type="submit" value="提交"/></div>
</form>

(5)特别注意代码中的错误提示信息的写法

(6)复选框中想要选中第一项的实现方法,formControlName后面的hobby值在ts中设置为要显示的初始化值,然后确保option中有上面的初始化值。

这个是响应式表单的写法:

<select name="hobby" id="hobby" formControlName="hobby">
      <option value="-请选择-" disabled>-请选择-</option>
      <option *ngFor="let hobby of model.hobbys" [value]='hobby'>{{hobby}}</option>
    </select>
补充模板式表单的写法:

<select name="hobby" id="hobby" [ngModel]= 'model.default'>
        <option value="-请选择-" disabled>-请选择-</option>
        <option *ngFor="let hobby of hobbys" [value]='hobby'>{{hobby}}</option>
      </select>

template-form.component.ts中的写法:

export class TemplateFormComponent implements OnInit {
  model = {
    'name' : 'zhangsan',
    'default':'-请选择-'
  }
  hobbys = ['Read', 'Music', 'Food'];
  constructor() { }
  ngOnInit() {
  }

  onSubmit(value) {
    console.log(value);
  }

}

大概的步骤和思路就是这样,如果还是有问题,建议down下代码自己实践一下。







本文转载:CSDN博客