typescript 使用Formaway和formbuilder生成角形的必填字段

nlejzf6q  于 2023-02-17  发布在  TypeScript
关注(0)|答案(1)|浏览(157)

我拼命地寻找几个小时,用ngif把一个简单的必填字段div放到我的各种表单控件上。 typescript :

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

@Component({
  selector: 'app-chargement-du-questionnaire',
  templateUrl: './chargement-du-questionnaire.component.html',
  styleUrls: ['./chargement-du-questionnaire.component.css']
})
export class ChargementDuQuestionnaireComponent {
  i: number = 0;
  errorMessage: string="";

  credit: FormGroup= new FormGroup({ 
typeDePret: new FormControl(''),
montantDuPret: new FormControl(''), 
tauxDuPret: new FormControl(''),
dureeDuPret: new FormControl(''),
dontDiffere: new FormControl(''), });

  constructor(private fb: FormBuilder) { }
      profileForm = this.fb.group({
      credit: this.fb.group({
        typeDePret: [''],
        montantDuPret: [Validators.required,Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$')],
        tauxDuPret: [''],
        dureeDuPret: [''],
        dontDiffere: [''],
        
      }),
      aliases: this.fb.array([
        this.fb.control('')
      ])
    });
    ngOnInit() {
      this.credit = new FormGroup({ 
        typeDePret: new FormControl(''),
        montantDuPret: new FormControl(Validators.required), 
        tauxDuPret: new FormControl(''),
        dureeDuPret: new FormControl(''),
        dontDiffere: new FormControl(''), });}
get montantDuPret() { return this.credit.get('montantDuPret')! }


    get aliasArray() {
      return this.profileForm.get('aliases') as FormArray;
    }
    
    addAlias() {
      if (this.aliasArray.length === 3) {
        this.errorMessage="Limiter à 3 prêts";
        setTimeout(() => {
          window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
        }, 10);
      } else {
        this.errorMessage = "";
        this.aliasArray.push(this.fb.control(''));
        setTimeout(() => {
          window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
        }, 10);
      }
    }
    removeAlias(index: number) {
      if (this.aliasArray.length === 3) {
        this.errorMessage="";
      }
      this.aliasArray.removeAt(index);
    }
    
  }

和html:

<form [formGroup]="profileForm"class="needs-validation" novalidate>
        <div formArrayName="aliases">
          <div class="form" *ngFor="let alias of aliasArray.controls; let i=index">
           <p> Pret n°{{i+1}}</p> 
           <div>
            <label for="typeDePret-{{ i}}">Type de prêt:</label><br>
          <select class="form-select" aria-label="Default select example"id="typeDePret-{{ i }}" [formControlName]="i">
            <option value="1">Prêt classique (amortissable)</option>
            <option value="2">In fine</option>
            <option value="3">Prêt à taux Zéro</option>
            <option value="4">Prêt relais</option>
          </select> 
        </div>

            <label for="montantDuPret-{{i}}">Montant du prêt</label><br>
            <div class="input-group mb-3">
              <input id="montantDuPret-{{i}}" type="text" [formControlName]="i" class="form-control" aria-label="Amount (to the nearest dollar)"formControlName="montantDuPret" id="montantDuPret"required>
              <span class="input-group-text">.00 €</span> 
              <div class="invalid-feedback" *ngIf="montantDuPret.invalid && montantDuPret.touched">
                <div *ngIf="montantDuPret.errors?.['required']">
                  Svp entrer le montant de votre pret.

                </div>
              </div>
            </div>
                    
            <label for="tauxDuPret-{{i}}">Taux du prêt</label><br>
            <div class="input-group mb-3">
              <input id="tauxDuPret-{{i}}" type="text" [formControlName]="i" class="form-control" aria-label="Amount (to the nearest dollar)"formControlName="tauxDuPret" id="tauxDuPret"required>
              <span class="input-group-text">%</span>  
            </div>
            <label for="dureeDuPret-{{i}}">Durée totale</label><br>
            <div class="input-group mb-3">
              <input id="dureeDuPret-{{i}}" type="text" [formControlName]="i" class="form-control" aria-label="Amount (to the nearest dollar)"formControlName="dureeDuPret" id="dureeDuPret"required>
              <span class="input-group-text">an(s)</span>
              <input id="dureeDuPret-{{i}}" type="text" [formControlName]="i" class="form-control" aria-label="Amount (to the nearest dollar)"formControlName="dureeDuPret" id="dureeDuPret"required>
              <span class="input-group-text">mois</span>   
            </div>
            <label for="dontDiffere-{{i}}">Dont différé</label><br>
            <select class="form-select" aria-label="Default select example"id="dontDiffere{{i}}" [formControlName]="i">
              <option value="1">1 mois</option>
              <option value="2">2 mois</option>
              <option value="3">3 mois</option>
              <option value="4">4 mois</option>
              <option value="5">5 mois</option>
              <option value="6">6 mois</option>
              <option value="7">7 mois</option>
              <option value="8">8 mois</option>
              <option value="9">9 mois</option>
              <option value="10">10 mois</option>
              <option value="11">11 mois</option>
              <option value="12">12 mois</option>
              <option value="13">13 mois</option>
              <option value="14">14 mois</option>
              <option value="15">15 mois</option>
              <option value="16">16 mois</option>
              <option value="17">17 mois</option>
              <option value="18">18 mois</option>
              <option value="19">19 mois</option>
              <option value="20">20 mois</option>
              <option value="21">21 mois</option>
              <option value="22">22 mois</option>
              <option value="23">23 mois</option>
              <option value="24">24 mois</option>
            </select> 
          </div>
        </div>
        <div class="error"*ngIf="errorMessage">{{errorMessage}}</div>
        <button (click)="removeAlias(i)">Remove Alias</button>
        <button type="button" (click)="addAlias()">+ Add another alias</button>
        
      </form>

我尝试了Angular 网站上描述的方法,但我没有渲染。。如果字段没有填充,就不会创建div。
我专注于"montantdupret"表单控件来做我的测试,告诉自己如果它能与一个表单控件一起工作,那么解决方案对其他表单控件也是一样的。

gupuwyp2

gupuwyp21#

您的montantDuPret指向this.credit.get('montantDuPret'),这不是您所期望的。
将条件更改为下面的代码,它将很好地运行。

<div class="invalid-feedback"
      *ngIf="aliasArray.at(i).invalid && aliasArray.at(i).touched">
      <div *ngIf="aliasArray.at(i).hasError('required')">
        Svp entrer le montant de votre pret.
      </div>
    </div>

参考:stackblitz

相关问题