Добавить выделение внутри Angular FormGroup и привязать выбранное значение

#javascript #angular #select #formgroups

#javascript #angular #выберите #formgroups

Вопрос:

У меня есть форма с вводом текста, а затем я хочу добавить выделение внутри этой формы:

Выбор представляет собой массив:

 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 amp;amp; result != null) {
          this.alertesService.create({
            notification: result ? result: null,
            ...this.alertForm.value
          }).subscribe(() => {
            this.router.navigate(['/alertes'])
          })      
        }
      });
    }
  }
}

 

Ответ №1:

Вы должны [formControlName] использовать form groups вместо ngmodel .

Пожалуйста, проверьте https://angular.io/api/forms/FormControlName