Angular 禁用按钮和垫输入错误消息

Angular disabling button and mat-input error message

我有一个文本框和一个按钮。文本框输入是 url 并且有一种验证 url 格式的方法,在此示例中为 isUrlFormatValid()

如果isUrlFormatValid() 失败则文本框下方会出现错误信息,按钮变为被动状态,无法点击。但我的问题是当页面第一次加载时,这个方法的结果自动为假,所以直接错误消息也出现在空框上。

<mat-card class="">
  <mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayoutGap="15px">

    <div>
      <mat-form-field>
        <mat-label>Enter link here</mat-label>
        <input type="url" matInput [(ngModel)]="domainName">
      </mat-form-field>
      <mat-error *ngIf="isUrlFormatValid()">
        Please enter the link in correct format
      </mat-error>
    </div>

  </mat-card-content>
  <div>
    <button type="button" id="search" class="" [disabled]="isUrlFormatValid()"
            (click)="addClicked()">Add Domain
    </button>
  </div>
</mat-card>

而ts文件中的方法定义为:

isUrlFormatValid() {
    const pattern = /^((((https?)(:\/\/))?((www)\.)?)?|mailto:(\w+\.?\w+)\@)([a-z0-9]+\.[a-z0-9]+)+$/;

    if (pattern.test(this.domainName)) {
      return false;
    }
    return true;
  }

如果我更改 ts 文件中的行:

if (pattern.test(this.domainName))

至:

if (pattern.test(this.domainName) || this.domainName == null) 

然后错误消息问题就解决了,但是这次按钮在启动时是可点击的,如果我写了一些是的,它正在工作,但是当页面第一次加载时它是活动的。

那么我该如何解决这个问题呢?

You may achieve the same without using an extra function. Just use some template driven form attributes & its control states as mentioned below. Also, It is a good practice to enclose your form elements in a <form> tag. So, if you use form, your scenario would be -

只需将其添加到您的 组件 class -

public pattern = /^((((https?)(:\/\/))?((www)\.)?)?|mailto:(\w+\.?\w+)\@)([a-z0-9]+\.[a-z0-9]+)+$/;

而您的 HTML 将是 -

<form #f="ngForm" (ngSubmit)="addClicked()">
    <mat-card class="">
        <mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayoutGap="15px">
            <div>
                <mat-form-field>
                    <mat-label>Enter link here</mat-label>
                    <input type="url" matInput [(ngModel)]="domainName" #url="ngModel" [class.is-invalid]="url.invalid && url.touched"
                        name="url" [pattern]="pattern" required>
                </mat-form-field>
                <mat-error *ngIf="url.invalid && (url.dirty || url.touched)">
                    Please enter the link in correct format
                </mat-error>
            </div>
        </mat-card-content>
        <div>
            <button type="button" id="search" class="" [disabled]="!f.valid">Add
                Domain
            </button>
        </div>
    </mat-card>
</form>