Angular 身份驗證控件
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
如果覺得本文對您有幫助~可以微信支持一下:




浙公網安備 33010602011771號