Angular 13中matTooltip显示错误信息时类型不匹配问题求助
解决Type 'unknown' is not assignable to type 'string'错误
以下是针对你的问题的具体修复步骤:
1. 修正TypeScript类型定义
首先明确类型,消除TypeScript的类型推断歧义:
import { Component, Input, OnInit } from '@angular/core'; import { FormControl, ErrorStateMatcher, ValidationErrors } from '@angular/forms'; import { Observable, startWith, tap, map } from 'rxjs'; // 定义错误类型的结构 type ErrorType = Record<string, (value: any) => string>; // 默认错误提示配置 const FORM_ERRORS: ErrorType = { required: () => '此字段为必填项', minlength: (val) => `最少需要${val.requiredLength}个字符`, // 可添加更多默认错误类型 }; @Component({ selector: 'app-validation-error', templateUrl: './validation-error.component.html', styleUrls: ['./validation-error.component.css'] }) export class ValidationErrorComponent implements OnInit { @Input() control!: FormControl; @Input() customErrors: ErrorType = {}; // 明确error$的类型为Observable<string> error$!: Observable<string>; constructor(public errorStateMatcher: ErrorStateMatcher) {} ngOnInit() { // 给setError函数明确参数和返回值类型 const setError = (ctrl: ValidationErrors | {}): string => { let errorStr = ''; // 使用forEach代替map(不需要返回数组) Object.entries(ctrl).forEach(([errorKey, errorValue]) => { const getError = this.customErrors[errorKey] || FORM_ERRORS[errorKey]; if (getError) { errorStr += `• ${getError(errorValue)}.\n`; } }); // 去除末尾换行符,避免空提示 return errorStr.trim(); }; this.error$ = this.control.statusChanges.pipe( tap(console.log), startWith(this.control.status), map(() => setError(this.control.errors || {})) ); } }
2. 修正HTML模板语法
修复异步管道的使用方式和绑定语法:
<mat-icon *ngIf="(error$ | async) as error && errorStateMatcher.isErrorState(control, null) && error" color="warn" [matTooltip]="error" matTooltipClass="tool-tip"> error_outline </mat-icon>
修复说明
- 明确类型定义:将
error$类型改为Observable<string>,让TypeScript清楚知道这个Observable只会输出字符串类型 - 优化setError函数:使用
ValidationErrors类型定义表单错误对象,同时明确返回值为字符串 - 修正模板逻辑:正确使用异步管道赋值,并增加非空判断,避免空字符串显示提示
- 添加引号绑定:
[matTooltip]="error"使用引号包裹,符合Angular绑定规范
内容的提问来源于stack exchange,提问作者Angad Patil
相关产品推荐
相关产品推荐

