【问题标题】:How to make error message to display for that particular input field using angular2如何使用angular2为该特定输入字段显示错误消息
【发布时间】:2018-09-28 05:42:33
【问题描述】:

我有多个输入字段,添加和更改在特定字段上工作正常,但是当进入错误消息部分时,如果一个字段中有输入字段错误,它会显示在所有其他字段中。但是,我希望为该特定字段显示错误。

HTML:

<md-card-content>
  <ul class="listClass">
    <li *ngFor="let media of videos; let i = index ">
      <div>
        <input type="text" name="{{media._id}}[i]" id="{{media._id}}[i]" class="form-control form-textbox input-text" [(ngModel)]="media.editText" #editText pattern="/^(ftp|http|https):\/\/[^ ]+$/" style="width: 58%;margin-left: 1%;">
      </div>
      <div *ngIf="errorMsg" style="color:red">
        {{errorMsg}}
      </div>
      <p class="inputimg" style="float: right;display: inline-block">
        <label *ngIf="media._id" class="img_change" (click)="change($event,media)" style="width: 100px;">Change Link</label>
        <label *ngIf="!media._id" class="img_change" (click)="changetext($event,media)" >Add Link</label>
      </p>
    </li>
  </ul>
</md-card-content>

TS:

    change(event: any, media) {
    if (media.editText.indexOf('https://www.youtube.com/embed') != -1) {
      this.errorMsg="";
      if (!media._id) {
        var data:any = {
          pin_id: this.pin_id,
          media_type: "video",
          image_path: media.editText
        } 
        this.ApiService
            .addLinkMedia(data)
            .subscribe(
              media => {
              })
      } else if(media._id) {
        var data:any = {
          media_id: media._id,
          image_path: media.editText
        } 
        this.ApiService
            .addLinkMedia(data)
            .subscribe(
              media => {
                this.loadMedias()
              }, error => {
              })
      }
    } else {
      this.errorMsg = "Please enter valid URL";
    }
}

这里我没有使用任何表单验证。

【问题讨论】:

  • 您能否在其他输入字段的位置显示更多的 html 代码或显示错误时的外观。如果您在每个字段下都有`*ngIf="errorMsg",那么它会显示在所有字段上,您必须为每个字段或至少一个数组使用不同的变量,或者更好的角度默认表单验证工具。
  • 你能举例说明你做了什么吗
  • 这是我提供视频链接的唯一输入字段
  • 你在使用 ng-repeat 吗?
  • @Sravan 不,我只使用了这么多代码

标签: html angular typescript


【解决方案1】:

你可以这样做。没有在 ts 文件中做任何事情。您可以仅使用表单控件来验证和显示验证消息。

<input id="name" name="name" class="form-control"
       required minlength="4" appForbiddenName="bob"
       [(ngModel)]="hero.name" #name="ngModel" >

<div *ngIf="name.invalid && (name.dirty || name.touched)"
     class="alert alert-danger">

  <div *ngIf="name.errors.required">
    Name is required.
  </div>
  <div *ngIf="name.errors.minlength">
    Name must be at least 4 characters long.
  </div>
  <div *ngIf="name.errors.forbiddenName">
    Name cannot be Bob.
  </div>

</div>

取自角度official doc

【讨论】:

  • 这只有在有表单控件在工作时才有效......这似乎不是这里的情况。
  • 在模板驱动的表单中,您可以显示这样的验证消息。如果您使用的是响应式表单,则必须以不同的方式执行此操作。在他使用模板驱动表单的问题中。这就是我发布这个答案的原因。
【解决方案2】:

查看下面的代码,您就会意识到自己的错误。您必须添加仅适用于当前输入的条件。

   <div [ngClass]="{ 'has-error': form.submitted && !username.valid }">
          <label for="firstName">First Name</label>
          <input type="text" name="firstName" [(ngModel)]="model.firstName" #firstName="ngModel" required />
          <div *ngIf="form.submitted && !firstName.valid">First Name is required  </div>
  </div>
  <div [ngClass]="{ 'has-error': form.submitted && !username.valid }">
          <label for="lastName">Last Name</label>
          <input type="text" name="lastName" [(ngModel)]="model.lastName" #lastName="ngModel" required />
         <div *ngIf="form.submitted && !lastName.valid" >Last Name is required</div>
  </div>

【讨论】:

  • 我的意思是你应该有这样的东西: *ngIf="errorMsg && inputErr[1]" 用于第一个输入和 *ngIf="errorMsg && inputErr[2]" 用于第二个输入。然后你用另外 1 个属性扩展你的方法,你在其中发送输入的索引,你使错误的 inputErr[] 索引为真。我希望这会有所帮助
【解决方案3】:

获取一个变量,该变量存储mediaid根据媒体 ID 相应地显示错误消息

  • 我正在分配 this.errorDiv[media._id] = true;; 以便我可以使用 errorDiv in *ngIf
  • 在 HTML 中,我使用了 *ngIf="errorMsg[media._id] &amp;&amp; (errorDiv[media._id])",它检查错误消息和特定 Id 并相应地显示错误消息

HTML:

<div>
    <input type="text" name="{{media._id}}[i]" id="{{media._id}}[i]" class="form-control form-textbox input-text" [(ngModel)]="media.editText" #editText pattern="/^(ftp|http|https):\/\/[^ ]+$/" style="width: 58%;margin-left: 1%;">
</div>
<div *ngIf="errorMsg[media._id] && (errorDiv[media._id])" style="color:red">
    {{errorMsg[media._id]}}
</div>
<p >
    <label *ngIf="media._id" (click)="change($event,media)">Change Link</label>
    <label *ngIf="!media._id" (click)="change($event,media)">Add Link</label>
</p>

组件:

public errorDiv = {};
public errorMsg = {};


    change(event: any, media) {
        if (media.editText.indexOf('https://www.youtube.com/embed') != -1) {
          this.errorMsg[media._id] = "";
          this.errorDiv[media._id] = "";
          if (!media._id) {
            var data:any = {
              pin_id: this.pin_id,
              media_type: "video",
              image_path: media.editText
            }
            this.ApiService
                .addLinkMedia(data)
                .subscribe(
                  media => {
                  })
          } else if(media._id) {
            var data:any = {
              media_id: media._id,
              image_path: media.editText
            }
            this.ApiService
                .addLinkMedia(data)
                .subscribe(
                  media => {
                    this.loadMedias()
                  }, error => {
                  })
          }
        } else {
          this.errorMsg[media._id] = "Please enter valid URL";
          this.errorDiv[media._id] = true;
        }
    }

【讨论】:

  • 如果在 2 个字段中输入了无效的 url 怎么办?那么错误信息将只显示在最新的。
  • 但是如果你看到个别字段上有提交按钮,但不是一次全部,因为它们被包裹在 *ngFor
  • 这不太可能是的,但是如果你输入一个无效的url而不提交,然后切换到另一个输入字段再次输入一个无效的url,那么错误消息将只显示在第二个字段上。
  • @Fussel,现在我通过将变量更改为对象并分配删除特定媒体的 errorMesage 来满足该要求。
  • @Sravan您之前的回答工作正常,在此我无法收到错误消息,请您自行发布之前的回答
【解决方案4】:

最好是您创建一个自定义验证器来检查您的输入,您被指出了正确的方向,但只是非常简短。创建一个新指令并在您的应用模块中提供它。

@Directive({
    selector: '[appValidURL]',
    providers: [{provide: NG_VALIDATORS, useExisting: URLValidatorDirective, multi: true}]
})
export class URLValidatorDirective implements Validator {
    @Input('appValidURL') url: string;

    validate(control: AbstractControl): {[key: string]: any} {
        return this.url && this.url.startsWith("https://www.youtube.com/embed") ? {value: control.value}}: null;
    }
}

然后在您的输入代码中使用类似这样的内容。

<input type="text" name="videourl" id="videourl" class="form-control" required appValidURL [(ngModel)]="media.editText">
<div *ngIf="videourl.invalid && (videourl.dirty || videourl.touched)" class="alert alert-danger">
   <div *ngIf="videourl.errors.required">
        VideoURL is required!
   </div>
   <div *ngIf="videourl.errors.url">
       It must be an embedded youtube video!
   </div>
</div>

我从来没有像这样使用过它,但它应该可以用一些小的 tweeks 来工作。

编辑: 这仅适用于单个输入字段,您可以尝试使用您的数组名称而不是“videourl”,不知道这是如何工作的。

【讨论】:

  • 感谢回复
【解决方案5】:

尝试将错误消息分别绑定到每个媒体对象:

HTML:

<md-card-content>
  <ul class="listClass">
    <li *ngFor="let media of videos; let i = index ">
      <div>
        <input type="text" name="{{media._id}}[i]" id="{{media._id}}[i]" class="form-control form-textbox input-text" [(ngModel)]="media.editText" #editText pattern="/^(ftp|http|https):\/\/[^ ]+$/" style="width: 58%;margin-left: 1%;">
      </div>
      <div *ngIf="media.errorMsg" style="color:red">
        {{media.errorMsg}}
      </div>
      <p class="inputimg" style="float: right;display: inline-block">
        <label *ngIf="media._id" class="img_change" (click)="change($event,media)" style="width: 100px;">Change Link</label>
        <label *ngIf="!media._id" class="img_change" (click)="changetext($event,media)" >Add Link</label>
      </p>
    </li>
  </ul>
</md-card-content>

TS:

    change(event: any, media) {
    if (media.editText.indexOf('https://www.youtube.com/embed') != -1) {
      media.errorMsg="";
      if (!media._id) {
        var data:any = {
          pin_id: this.pin_id,
          media_type: "video",
          image_path: media.editText
        } 
        this.ApiService
            .addLinkMedia(data)
            .subscribe(
              media => {
              })
      } else if(media._id) {
        var data:any = {
          media_id: media._id,
          image_path: media.editText
        } 
        this.ApiService
            .addLinkMedia(data)
            .subscribe(
              media => {
                this.loadMedias()
              }, error => {
              })
      }
    } else {
      media.errorMsg = "Please enter valid URL";
    }
}

【讨论】:

  • 感谢您的回复,即使这工作正常,所以我赞成
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 2022-01-19
相关资源
最近更新 更多