Angular Material: mat-错误封装
Angular Material: mat-error encapsulation
我想将 mat-error
封装到它自己的组件中,因为文本往往很长。于是我想到:
<form [formGroup]="form">
<mat-form-field>
<input matInput formControlName="title" placeholder="Title" required />
<app-mat-error-too-long [ctrl]="form.controls.title"></app-mat-error-too-long>
</mat-form-field>
</form>
和
<mat-error *ngIf="ctrl.hasError('maxlength')">
<span >Input too long</span>
<span> </span>
<span>{{ctrl.getError('maxlength').actualLength}}/{{ctrl.getError('maxlength').requiredLength}}</span>
</mat-error>
组件:
import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { AbstractControl } from '@angular/forms';
@Component({
selector: 'app-mat-error-too-long',
templateUrl: './mat-error-too-long.component.html',
styleUrls: ['./mat-error-too-long.component.scss'],
})
export class MatErrorTooLongComponent implements OnInit {
@Input() ctrl: AbstractControl
constructor() { }
ngOnInit(): void {
}
}
但是如果我这样做,错误就不会正确显示并且就在组件下面:
mat-error
需要直接在 mat-form-field 中使用才能正常工作。所以你可以做的是为你的 child 组件使用属性选择器并将其附加到 mat-error
:
<mat-form-field>
<input matInput formControlName="title" placeholder="Title" required />
<mat-error app-mat-error-too-long [ctrl]="form.controls.title"></mat-error>
</mat-form-field>
那么您当然需要从 child 中删除 mat-error
标签,而只显示您的消息。 child 选择器也需要改变,用括号括起来:
selector: '[app-mat-error-too-long]'
我想将 mat-error
封装到它自己的组件中,因为文本往往很长。于是我想到:
<form [formGroup]="form">
<mat-form-field>
<input matInput formControlName="title" placeholder="Title" required />
<app-mat-error-too-long [ctrl]="form.controls.title"></app-mat-error-too-long>
</mat-form-field>
</form>
和
<mat-error *ngIf="ctrl.hasError('maxlength')">
<span >Input too long</span>
<span> </span>
<span>{{ctrl.getError('maxlength').actualLength}}/{{ctrl.getError('maxlength').requiredLength}}</span>
</mat-error>
组件:
import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { AbstractControl } from '@angular/forms';
@Component({
selector: 'app-mat-error-too-long',
templateUrl: './mat-error-too-long.component.html',
styleUrls: ['./mat-error-too-long.component.scss'],
})
export class MatErrorTooLongComponent implements OnInit {
@Input() ctrl: AbstractControl
constructor() { }
ngOnInit(): void {
}
}
但是如果我这样做,错误就不会正确显示并且就在组件下面:
mat-error
需要直接在 mat-form-field 中使用才能正常工作。所以你可以做的是为你的 child 组件使用属性选择器并将其附加到 mat-error
:
<mat-form-field>
<input matInput formControlName="title" placeholder="Title" required />
<mat-error app-mat-error-too-long [ctrl]="form.controls.title"></mat-error>
</mat-form-field>
那么您当然需要从 child 中删除 mat-error
标签,而只显示您的消息。 child 选择器也需要改变,用括号括起来:
selector: '[app-mat-error-too-long]'