Add Select inside Angular FormGroup and bind selected value

1.1k Views Asked by At

I have a form with a text input and then I want to add a select inside that Form:

The select is an array:

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

I want to bind the value selected on the select. I have a var called select to store which the user has selected. I have to add the selected inside formGroup?

Also I am getting this error:

ngModel cannot be used to register form controls with a parent formGroup directive

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'])
          })      
        }
      });
    }
  }
}

1

There are 1 best solutions below

0
On

You should [formControlName] with form groups, instead of ngmodel.

Please check https://angular.io/api/forms/FormControlName