Angular 6-输入控件悬停时出现验证错误消息

时间:2018-12-05 05:28:06

标签: angular forms reactive

当前使用角度6反应形式,需要在输入控件悬停时显示验证消息。

2 个答案:

答案 0 :(得分:1)

在这里,尝试一下。我在这里使用CSS Tooltip

p {
  font-family: Lato;
}

.tooltip {
    position: relative;
    display: inline-block;
    border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}

/* Tooltip text */
.tooltip .tooltiptext {
    visibility: hidden;
    width: 120px;
    background-color: black;
    color: #fff;
    text-align: center;
    padding: 5px 0;
    border-radius: 6px;

    /* Position the tooltip text - see examples below! */
    position: absolute;
    z-index: 1;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
    visibility: visible;
}

在您的模板中:

<form [formGroup]="form" (submit)="onSubmit()">
  <div class="tooltip">Control: <input type="text" formControlName="control">
    <span class="tooltiptext">This field is Required</span>
  </div>

  <br><br>

  <button [disabled]="form.invalid">Submit</button>
</form>

您的组件:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  form: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      control: [null, Validators.required]
    });
  }

  onSubmit() {

  }

}

这是您推荐的Working Sample StackBlitz

答案 1 :(得分:0)

以下是如何使用angular material的答案,但是您可以根据需要进行选择

选项鼠标事件

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Email" [formControl]="emailFormControl"
         (mouseenter) ="showError = true; "  (mouseleave) ="showError = false;">
    <mat-error *ngIf="showError  && emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
      Please enter a valid email address
    </mat-error>
  </mat-form-field>
</form>

选项工具提示

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Email" [formControl]="emailFormControl"
         matTooltip="Error" matTooltipDisabled="!emailFormControl.hasError('email')">

  </mat-form-field>
</form>