我有一个使用angular5的项目构建,并且有很多重复的输入组件,如:
cd D:\Jenkins\workspace\bfsearch\bin
组件应该输入FormControl,当它触摸时,显示错误。 有没有什么方法可以把它写成共享组件?
答案 0 :(得分:0)
首先在共享模块中创建一个ValidationErrorComponent:
import {Component, Input, OnInit} from '@angular/core';
import {AbstractControl, FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'validation-error',
templateUrl: 'validation-error.component.html'
})
export class ValidationErrorComponent implements OnInit {
@Input('control')
public control: AbstractControl;
constructor() {
}
ngOnInit(): void {
if (!this.control) {
this.control = new FormControl();
}
}
}
然后在validation-error.component.html
中<div class="help-block" *ngIf="control?.touched">
<span class="text-danger" *ngIf="control.hasError('required')">Field is required</span>
<span class="text-danger" *ngIf="control.hasError('email')">The email is invalid</span>
<span class="text-danger" *ngIf="control.hasError('min')">The value is too small</span>
<span class="text-danger" *ngIf="control.hasError('max')">The value is too large</span>
<span class="text-danger" *ngIf="control.hasError('minlength')">The field is too short</span>
<span class="text-danger" *ngIf="control.hasError('maxlength')">Maximum of 35 characters</span>
<span class="text-danger" *ngIf="control.hasError('commaError')">Comma should not contained</span>
<span class="text-danger" *ngIf="control.hasError('customError')">This field should only contains letters/numbers and / . # -.</span>
<span class="text-danger" *ngIf="control.hasError('numberLetterOnlyError')">This field should only contains letters and numbers</span>
<span class="text-danger" *ngIf="control.hasError('numberLetterSpace')">This field should only contains letters/numbers/spaces </span>
<span class="text-danger" *ngIf="control.hasError('customError')">This field should only contains only letters/numbers and / . # - </span>
<span class="text-danger" *ngIf="control.hasError('matchOther')">The repeat password is not match.</span>
<span class="text-danger" *ngIf="control.hasError('clearingCodeRequiredError')">clearingCodeRequiredError Error</span>
</div>
注意到像clearingCodeRequiredError这样的错误是您的自定义错误。
最后,你可以通过导入共享模块和组件html代码来使用它:
<section class="col col-6">
<label class="input">
Name
<span style="color: red">*</span>
<input type="text"
formControlName="name"
[(ngModel)]="pricingPlan.name"
name="name"
placeholder="">
<validation-error
[control]="myForm.get('name')"></validation-error>
</label>
</section>
希望它可以提供帮助!