>

表单管理

- 编辑:www.bifa688.com -

表单管理

错误描述

在项目中,可以使用angular中的 @angular/forms模块处理表单,但是并不需要在app.module中引用@angular/forms模块,因为在app.module中已经引入了@angular/platform-browser模块,而在@angular/platform-browser模块中又导出了 @angular/forms 。也就是说,引入@angular/platform-browser模块之后就可以直接使用@angular/forms模块中提供的组件等内容。

错误描述

当form表单加FormGroup属性时报错 Can't bind to 'formGroup' since it isn't a known property of 'form'

从@angular/forms中引入需要用到的内容

必发88官网,当form表单加FormGroup属性时报错 Can't bind to 'formGroup' since it isn't a known property of 'form'

 <form nz-form [formGroup]="valForm" (ngSubmit)="submit()" role="form">
                <div nz-form-item>
                    <div nz-form-control [nzValidateStatus]="valForm.controls.email">
                        <nz-input formControlName="email" [nzPlaceHolder]="'邮箱'" [nzSize]="'large'">
                            <ng-template #suffix>
                                <i class="anticon anticon-mail"></i>
                            </ng-template>
                        </nz-input>
                        <div nz-form-explain *ngIf="valForm.controls.email.dirty&&valForm.controls.email.hasError('required')">邮箱必填</div>
                    </div>
                </div>
                <div nz-form-item>
                    <div nz-form-control [nzValidateStatus]="valForm.controls.password">
                        <nz-input formControlName="password" [nzPlaceHolder]="'密码'" [nzType]="'password'" [nzSize]="'large'">
                            <ng-template #suffix>
                                <i class="anticon anticon-lock"></i>
                            </ng-template>
                        </nz-input>
                        <div nz-form-explain *ngIf="valForm.controls.password.dirty&&valForm.controls.password.hasError('required')">密码必填</div>
                    </div>
                </div>
                <div nz-form-item nz-row>
                    <div nz-col [nzSpan]="12">
                        <label nz-checkbox formControlName="remember_me">
                            记住密码
                        </label>
                    </div>
                    <div nz-col [nzSpan]="12" class="text-right">
                        <a [routerLink]="['/forget']">注册</a>
                    </div>
                </div>
                <div nz-form-item nz-row>
                    <div nz-col [nzSpan]="24">
                        <button nz-button [disabled]="!valForm.valid" [nzType]="'primary'" [nzSize]="'large'" class="ant-btn__block">
                            登录
                        </button>
                    </div>
                </div>
            </form>
import {FormBuilder, Validators, FormGroup} from '@angular/forms';
 <form nz-form [formGroup]="valForm" (ngSubmit)="submit()" role="form">
                <div nz-form-item>
                    <div nz-form-control [nzValidateStatus]="valForm.controls.email">
                        <nz-input formControlName="email" [nzPlaceHolder]="'邮箱'" [nzSize]="'large'">
                            <ng-template #suffix>
                                <i class="anticon anticon-mail"></i>
                            </ng-template>
                        </nz-input>
                        <div nz-form-explain *ngIf="valForm.controls.email.dirty&&valForm.controls.email.hasError('required')">邮箱必填</div>
                    </div>
                </div>
                <div nz-form-item>
                    <div nz-form-control [nzValidateStatus]="valForm.controls.password">
                        <nz-input formControlName="password" [nzPlaceHolder]="'密码'" [nzType]="'password'" [nzSize]="'large'">
                            <ng-template #suffix>
                                <i class="anticon anticon-lock"></i>
                            </ng-template>
                        </nz-input>
                        <div nz-form-explain *ngIf="valForm.controls.password.dirty&&valForm.controls.password.hasError('required')">密码必填</div>
                    </div>
                </div>
                <div nz-form-item nz-row>
                    <div nz-col [nzSpan]="12">
                        <label nz-checkbox formControlName="remember_me">
                            记住密码
                        </label>
                    </div>
                    <div nz-col [nzSpan]="12" class="text-right">
                        <a [routerLink]="['/forget']">注册</a>
                    </div>
                </div>
                <div nz-form-item nz-row>
                    <div nz-col [nzSpan]="24">
                        <button nz-button [disabled]="!valForm.valid" [nzType]="'primary'" [nzSize]="'large'" class="ant-btn__block">
                            登录
                        </button>
                    </div>
                </div>
            </form>

原因分析与解决方案

对应的表单初始化如下:formBuilder.group中的字段就是form表单中对应的字段,Validators 用于校验,规则根据实际情况配置。

原因分析与解决方案

在使用form表单时,如果用到了form-group与formControlName,需要在app.module.ts中的import引入的不仅仅有FormsModule,还要引入ReactiveFormsModule。如果是懒加载,则按需在各自的module中引入。如下:

 constructor(private navCtrl: NavController, private navParams: NavParams, private formBuilder: FormBuilder, private viewCtrl: ViewController, private events: Events, private httpService: HttpService, private storageService: StorageService, private nativeService: NativeService) { this.loginForm = formBuilder.group({ username: ['', Validators.compose([Validators.minLength, Validators.maxLength, Validators.required,])], password: ['', Validators.compose([Validators.required, Validators.minLength; this.username = this.loginForm.controls['username']; this.password = this.loginForm.controls['password']; }

在使用form表单时,如果用到了form-group与formControlName,需要在app.module.ts中的import引入的不仅仅有FormsModule,还要引入ReactiveFormsModule。如果是懒加载,则按需在各自的module中引入。如下:

 

至此,表单初始化完成,下面是对应的 模板代码

 

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { LoginComponent } from './login/login.component';

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        ReactiveFormsModule
           ],
    declarations: [
        LoginComponent
    ],
    providers: [
    ]
})
export class AccountModule {

}
 <ion-row> <ion-col> <form [formGroup]="loginForm" ="login(loginForm.value)" novalidate> <ion-row> <ion-col> <ion-list inset > <ion-item [class.error]="!username.valid && username.touched"> <ion-label fixed>请输入账号</ion-label> <ion-input type="text" [formControl]="username" clearInput=true></ion-input> </ion-item> <!--<div *ngIf="username.hasError('required') && username.touched" >*请输入用户名</div>--> <!--<div *ngIf="(username.hasError('minlength')||username.hasError('maxlength')||username.hasError('pattern')) && username.touched" >*请输入正确的电话号码</div>--> <ion-item> <ion-label fixed>请输入密码</ion-label> <ion-input type="password" [formControl]="password" clearInput=true></ion-input> </ion-item> <!--<div *ngIf="password.hasError('required') && password.touched" >*请输入密码</div>--> <!--<div *ngIf="(password.hasError('minlength')) && password.touched" >*密码长度最少为六位</div>--> </ion-list> </ion-col> </ion-row> <ion-row> <ion-col> <div style="text-align: center"> <button ion-button round type="submit" [disabled]="!loginForm.valid">测&nbsp;&nbsp;试</button> </div> </ion-col> </ion-row> </form> </ion-col> </ion-row>
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { LoginComponent } from './login/login.component';

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        ReactiveFormsModule
           ],
    declarations: [
        LoginComponent
    ],
    providers: [
    ]
})
export class AccountModule {

}

 

对应的 表单提交函数如下

 

 

login { this.nativeService.showLoading('loading...'); let password = Md5.hashStr(this.password).toString(), params = { username: value.username, password: value.password, }; this.httpService.login('/oauth/token', params).then(result => { //xxx }).catch(error => { //xxx }); }

 

 

ngSubmit 是一个@output属性,将表单的值以键值对的方式组装成一个对象返回。

 

对以上代码稍做修改 login.ts

 constructor(private navCtrl: NavController, private navParams: NavParams, private formBuilder: FormBuilder, private viewCtrl: ViewController, private events: Events, private httpService: HttpService, private storageService: StorageService, private nativeService: NativeService) { this.loginForm = formBuilder.group({ username: ['', Validators.compose([Validators.minLength, Validators.maxLength, Validators.required, ])], password: ['', Validators.compose([Validators.required, Validators.minLength, this.passValidator])] }); this.username = this.loginForm.controls['username']; this.password = this.loginForm.controls['password']; }

注意上面用到了一个自定义校验函数 this.passValidator ,该函数内容如下

 /** * 自定义检验函数 * @param {FormControl} control * @returns {{username: {info: string}}} */ passValidator(control: FormControl){ const value = control.value; return value? null : {password: {info: '这是自定义校验函数检查出来的错误'}}; }

为了查看测试结果,需要修改一下模板文件 login.html

 <ion-row> <ion-col> <form [formGroup]="loginForm" ="login(loginForm.value)" novalidate> <ion-row> <ion-col> <ion-list inset > <ion-item [class.error]="!username.valid && username.touched"> <ion-label fixed>请输入账号</ion-label> <ion-input type="text" [formControl]="username" clearInput=true></ion-input> </ion-item> <ion-item> <ion-label fixed>请输入密码</ion-label> <ion-input type="password" [formControl]="password" clearInput=true></ion-input> </ion-item> <div *ngIf="password.hasError('required') && password.touched" >{{loginForm.getError('password', 'password')?.info}}</div> </ion-list> </ion-col> </ion-row> <ion-row> <ion-col> <div style="text-align: center"> <button ion-button round type="submit" [disabled]="!loginForm.valid">测&nbsp;&nbsp;试</button> </div> </ion-col> </ion-row> </form> </ion-col> </ion-row>仅仅是加了 <div *ngIf="password.hasError('required') && password.touched" >{{loginForm.getError('password', 'password')?.info}}</div> 当校验不通过的时候,就会在这个div上显示 在 login.ts 中定义的 提示信息。

以下是测试结果,仔细看

必发88官网 1

本文由必发88官网发布,转载请注明来源:表单管理