简体   繁体   English

Ngmodel 表单验证

[英]Ngmodel Forms Validation

I have an Angular ngModel Forms , I wanna make something that when the first input is filled, the second change from enable to disable, and when the second is filled, the third also change to enable.我有一个 Angular ngModel Forms ,我想做一些事情,当第一个输入被填充时,第二个从启用变为禁用,当第二个被填充时,第三个也变为启用。

This a screen of my forms screenshot这是我的表单屏幕截图

So I have tried with this but it doesn't work:所以我试过这个,但它不起作用:

 <div class="pl-2">
    <div class="form-group">
       <label for="exampleInputEmail1">Nom:</label>
       <input
          [(ngModel)]="nom"
          type="text"
          class="form-control"
          id="exampleInputEmail1"
          aria-describedby="emailHelp"
          placeholder="Nom"
        />
     </div>
    
     <div class="form-group">
        <label for="exampleInputEmail1">Prenom:</label>
        <input
           type="text"
           [(ngModel)]="prenom"
           class="form-control"
           id="exampleInputEmail1"
           aria-describedby="emailHelp"
           placeholder="Prenom"
           [disabled]="disabled"
         />
      </div>
nom = ""
prenom = ""
disabled: boolean = true;
    
 ngOnInit(): void {  
    this.disabled = true;
    
    if(this.nom.length !== 0)
    {
       this.disabled=false
    }
 }

How can I fix it?我该如何解决?

According to your ts code, disabled has a value of true at the beginning, which your second input is already disabled.根据您的ts代码, disabled一开始的值为true ,您的第二个输入已被禁用。

I would suggest adding an input event for enabling/disabling your second input capturing the value of nom like this:我建议添加一个input事件来启用/禁用您的第二个输入,捕获nom的值,如下所示:

    <input
       [(ngModel)]="nom"
       type="text"
       class="form-control"
       id="exampleInputEmail1"
       aria-describedby="emailHelp"
       placeholder="Nom"
       (input)="onInputEvent()"
    />

    <!-- your second input -->
     <input
         type="text"
         [(ngModel)]="prenom"
         class="form-control"
         id="exampleInputEmail1"
         aria-describedby="emailHelp"
         placeholder="Prenom"
         [disabled]="disabled"
      />

In your .ts file:在您的.ts文件中:

....
disabled = false;

onInputEvent(): void {
  this.disabled = this.nom.length > 0; // disables your second input
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM