【问题标题】:How can I set the value of a form field basing on the value selected into another field using Angular rective form?如何根据使用 Angular 反应表单选择到另一个字段的值来设置表单字段的值?
【发布时间】:2020-12-17 08:48:00
【问题描述】:

我是 Angular 的新手,我正在开发一个使用 PrimeNG 的直通形式的应用程序。

我有以下问题,我找不到解决方案。基本上当用户用一个值填充一个特定的字段时,另一个字段必须用一个特定的值填充。

我试着详细解释一下。

我有这 2 个字段:

其中Referent字段代表一个人,Ruole referente字段代表所选人员的角色。

例如,我可以将 Mario Rossi 设置为 Referente 字段的值:

如您所见,Referente 字段基于基于可能用户列表的自动完成输入表单。对于自动完成中使用的用户列表中的每个用户,还有特定的用户角色信息。

这是我对这两个字段的 HTML 代码:

<div class="row">
  <div class="col-2">
    <p>Referente</p>
  </div>
  <div class="col-10">
    <!--<input id="referente" formControlName="referente" type="text" pInputText />-->

    <p-autoComplete id="referente"
                formControlName="referente"
                [suggestions]="filteredPeople"
                (completeMethod)="filterPeople($event)"
                field="complete_name"
                [dropdown]="true">
      <ng-template let-person pTemplate="item">
      <div class="people-item">
          <!--<img src="assets/showcase/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + person.avatar.toLowerCase()" />-->
          <img src="assets/img/people/{{person.avatar}}" [class]="'flag flag-' + person.avatar.toLowerCase()" />
          <span>{{person.complete_name}}</span>
      </div>
      </ng-template>
  </p-autoComplete>

  </div>
</div>

<div class="row">
  <div class="col-2">
    <p>Ruolo referente</p>
  </div>
  <div class="col-10">
    <input id="ruoloReferente" formControlName="ruoloReferente" type="text" pInputText value= />
  </div>
</div>

如前所述,这是一种反应式表单,因此目前第二个 RuoloReferente 字段正在使用此 formControlName="ruoloReferente" 在表单中设置控件值.我希望用户在 Referente 字段中选择用户之后使用与所选用户相关的正确信息。

基本上,当我从列表中选择用户时,它使用 **{{person.complete_name}} 相关对象字段来显示名称。此对象还包含其他字段 person.role,必须使用这些字段来评估其他字段内容。

如何正确实现此行为?我错过了什么?

【问题讨论】:

    标签: angular primeng angular-reactive-forms


    【解决方案1】:

    您可以在第一个选择框的更改事件期间设置表单控件值。因此,我创建了一个简单的 stackblitz,您可以在其中清楚地了解它。

    你可以找到stackblitz链接here

    解释

    在上面的堆栈闪电战中,会有两个选择框。如果您在第一次选择中选择了某个值,那么第二次选择中将填充相同的值。

    app.component.html

    <select class="custom-select" (change)="changeCity($event)" formControlName="cityName">
                  <option value="">Choose your city</option>
                  <option *ngFor="let city of City" [ngValue]="city">{{city}}</option>
    </select>
    

    如您所见,这里有一个更改事件,在该更改事件期间,我将在 typescript 中设置第二个选择值。

    app.component.ts

      changeCity(e) {
        this.registrationForm.get('cityNameDup').setValue(e.target.value);
      }
    

    希望这能解决您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      相关资源
      最近更新 更多