ng g c shared/identity-input
ng g c shared/area-list
1,添加领域对象
export enum IdentityType { IdCard = 0, Insurance, Passport, Militory, Other } export interface Address { provice: string, city: string, district: string, street?: string } export interface Identity { identityNo: string; identityType: IdentityType } export interface User { id?: string; email: string; name?: string; password?: string; avatar?: string; projectIds?: string[]; taskIds?: string[]; address?: Address; dateOfBirth?: string; identity?: Identity; }
2,身份输入UI template
<div> <mat-form-field> <mat-select placeholder="证件类型" (change)="onIdTypeChange($event.value)" [(ngModel)]="identity.identityType"> <mat-option *ngFor="let type of identityTypes" [value]="type.value"> {{ type.label }} </mat-option> </mat-select> </mat-form-field> </div> <div class="id-input"> <mat-form-field class="full-width"> <input matInput type="text" placeholder="证件号码" (change)="onIdNoChange($event.target.value)" [(ngModel)]="identity.identityNo" /> <mat-error>证件号码输入有误</mat-error> </mat-form-field> </div>
3, 身份类型和身份号码
private _idType = new Subject<IdentityType>(); private _idNo = new Subject<string>(); private _sub: Subscription; ngOnInit(): void { const idType$ = this.idType; const idNo$ = this.idNo; const val$ = combineLatest([idType$, idNo$]).pipe( map(([_type, _no]) => ({ identityType: _type, identityNo: _no })) ); this._sub = val$.subscribe(v => { this.identity = v; this.propagateChange(v); }); } onIdTypeChange(idType: IdentityType) { this._idType.next(idType); } onIdNoChange(idNo: string) { this._idNo.next(idNo); } private get idType(): Observable<IdentityType> { return this._idType.asObservable(); } private get idNo(): Observable<string> { return this._idNo.asObservable(); }
在UI中调用
1,在注册组件中新开一个tab使用
<mat-tab label="个人信息"> <div class="full-width"> <app-identity-input formControlName="identity"></app-identity-input> </div> <div class="full-width"> <app-age-input formControlName="dateOfBirth"></app-age-input> </div> <div class="full-width"> <app-area-list formControlName="address"></app-area-list> </div> </mat-tab>
2,希望输入身份证的时候同时改变出生日期和地址
自定义表单控件和普通表单控件一样,都可以通过valueChanges模式获得流。
const identity = this.form.get('identity'); if (!identity) { return; } const id$ = identity.valueChanges.pipe( debounceTime(300), //滤波 filter(v => identity.valid) //验证通过的时候才能把数据放出来 );
3,订阅流,从身份信息中读取出来有用的信息,比如生日和地址,把它set回其他两个控件。
100