【问题标题】:Add Select inside Angular FormGroup and bind selected value在 Angular FormGroup 中添加 Select 并绑定选定的值
【发布时间】:2021-03-10 03:53:56
【问题描述】:

我有一个带有文本输入的表单,然后我想在该表单中添加一个选择:

select 是一个数组:

typeAlert: TypeAlert[] = [
    { value: 'MEDICAL'},
    { value: 'POLICE'},
    { value: 'FIRE'}
  ];

我想绑定选择时选择的值。我有一个名为 select 的变量来存储用户选择的内容。我必须在 formGroup 中添加选定的内容?

我也收到此错误:

ngModel 不能用于使用父 formGroup 指令注册表单控件

component.html

<form class="container" [formGroup]="alertForm">
  <div class="actions">
    <div class="action" [routerLink]="['/alertes']">
      <span>Torna a Alertes</span>
    </div>
    <div class="space"></div>
    <button class="action" (click)="save()" [disabled]="!alertForm.valid">
      Guardar
    </button>
  </div>

  
  <div class="dades">
    <div class="card">
      <div class="card-title">
        <b>Title</b>
      </div>
      <div class="card-content">
        <mat-form-field>
          <mat-label>Title</mat-label>
          <input formControlName="title" matInput>
        </mat-form-field>
      </div>
    </div>
  </div>
  <div class="dades">
    <div class="card">
      <div class="card-title">
        <b>Type Alert</b>
      </div>
      <div class="card-content">
        <mat-form-field appearance="fill">
          <mat-label>Type Alert</mat-label>
          <mat-select [(ngModel)]="selected">
            <mat-option *ngFor="let alert of typeAlert" [value]="alert.value">
              {{alert.value}}
            </mat-option>
          </mat-select>
        </mat-form-field>
      </div>
    </div>
  </div>
</form>

component.ts:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AlertesService } from 'src/app/core/services/alertes.service';
import { MatDialog } from '@angular/material/dialog';
import { DialogNotificationsComponent } from 'src/app/shared/components/dialog-notifications/dialog-notifications.component';
interface TypeAlert {
  value: string;
}
@Component({
  selector: 'app-alert',
  templateUrl: './alert.component.html',
  styleUrls: ['./alert.component.scss']
})
export class AlertComponent implements OnInit, OnDestroy {

  typeAlert: TypeAlert[] = [
    { value: 'MEDICAL'},
    { value: 'POLICE'},
    { value: 'FIRE'}
  ];

  selected: string = this.typeAlert[0].value;
  alertForm: FormGroup;
  alert;

  constructor(
    private alertesService: AlertesService, 
    private route: ActivatedRoute,
    private router: Router,
    public dialog: MatDialog
  ) { }

  ngOnInit() {
    this.alert = this.route.snapshot.data.alert;
    this.initForm();

  }

  ngOnDestroy() {
  }

  initForm() {
    this.alertForm = new FormGroup({
      title: new FormControl(this.alert ? this.alert.title : '', [Validators.required]),
    });
  }

  save() {
    console.log(this.selected);
    if(this.alert) {
      this.alertesService.update(this.alert._id, this.alertForm.value).subscribe(() => {
        this.router.navigate(['/alertes'])
      })  
    }
    else {
      const dialogRef = this.dialog.open(DialogNotificationsComponent, {
        width: '600px',
        data: {title: "Nova alerta", msg: this.alertForm.value.title}
      });
      dialogRef.afterClosed().subscribe(result => {
        console.log(result);
        if(result != undefined && result != null) {
          this.alertesService.create({
            notification: result ? result: null,
            ...this.alertForm.value
          }).subscribe(() => {
            this.router.navigate(['/alertes'])
          })      
        }
      });
    }
  }
}

【问题讨论】:

    标签: javascript angular select formgroups


    【解决方案1】:

    您应该 [formControlName] 使用表单组,而不是 ngmodel。

    请查看https://angular.io/api/forms/FormControlName

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 2015-03-24
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      相关资源
      最近更新 更多