Jak zrobić, aby wyświetlić komunikat o błędzie na tym polu szczególnie wejściowego używając angular2

głosy
1

Mam wiele pól wejściowych, dodawanie i zmianę pracują dobrze z danym fieds, ale kiedy przychodzi do błędu sekcję wiadomości, jeśli nie ma wejścia eror pole w jednym polu jest wyświetlany we wszystkich innych dziedzinach. Ale chcę, aby wyświetlić błąd na tej konkretnej dziedzinie.

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;
    }
}

tu nie miałaś wykorzystane jakiekolwiek walidacje formularza.

Utwórz 18/04/2018 o 05:39
źródło użytkownik
W innych językach...                            


5 odpowiedzi

głosy
3

Weź zmienna, która przechowuje idof mediaa komunikat o błędzie wyświetlacz odpowiednio w zależności od ID mediów .

  • I m przypisywanie this.errorDiv[media._id] = true;;tak, że można używać errorDivw * ngIf
  • W HTML użyłem *ngIf="errorMsg[media._id] && (errorDiv[media._id])"który sprawdza się komunikat o błędzie i konkretny identyfikator i wyświetlanie komunikatu o błędzie Odpowiednio

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>

Składnik:

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;
        }
    }
Odpowiedział 18/04/2018 o 06:17
źródło użytkownik

głosy
1

Spróbuj wiążące się komunikat o błędzie do każdego obiektu osobno mediów:

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";
    }
}
Odpowiedział 18/04/2018 o 06:25
źródło użytkownik

głosy
0

Najlepiej jest utworzyć niestandardowe walidatora Sprawdzanie wejście, zostałeś wskazywanego właściwym kierunku, ale tylko bardzo krótko. Tworzenie nowej dyrektywy i zapewnić go w module aplikacji.

@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;
    }
}

Następnie w kodzie wejściowym użyć czegoś takiego.

<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>

Nigdy nie używał go w ten sposób, ale to powinno działać może z niewielkimi tweeks.

Edit: To jest tylko dla jednego pola wejściowego, twój może spróbować tho korzystać z nazwy tablicy zamiast „videoURL”, nie wiem, jak to działa.

Odpowiedział 18/04/2018 o 06:19
źródło użytkownik

głosy
0

Zobacz poniższy kod i będzie realizować swój błąd. Należy dodać warunek, który jest przeznaczony wyłącznie do bieżącego wejścia.

   <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>
Odpowiedział 18/04/2018 o 05:55
źródło użytkownik

głosy
0

Można zrobić soething tak. Nie robiąc nic w ts pliku. Możesz potwierdzić i pokazać wiadomości walidacji tylko przy użyciu elementów sterujących formularza.

<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>

Zrobione z kątowym oficjalnego dokumentu

Odpowiedział 18/04/2018 o 05:46
źródło użytkownik

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more