Я разрабатываю модал в Angular, и в этом режиме есть таблица с x объектами, а внутри этого объекта есть обязательное поле, наблюдение на экране:
Список объектов
Однако мне нужно, чтобы это поле было обязательным, но при отправке или обмене одного из полей оно обвиняет во всех полях ошибки ... и я хотел, чтобы проверка была индивидуальной для каждого поля. элемент
Список объектов после сохранения или изменения одного из значений
rating-course.component. html:
<div class="row" style="padding-top: 10px">
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-striped" id="questionsRating">
<thead>
<tr>
<th width="3%">Item</th>
<th width="60%">Critério</th>
<th width="37%">Avaliação</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let question of rating.questions;">
<td>{{question.itemseqita}}</td>
<td>{{question.descita}}</td>
<td>
<select class="form-control"
(change)="avaliarCriterio(question, $event.target.value)"
[ngClass]="{'is-valid': !formRating.controls['indicetpr'].errors, 'is-invalid': formRating.controls['indicetpr'].errors }"
name="indicetpr"
formControlName="indicetpr"
[ngModelOptions]="{standalone: true}"
id="indicetpr">
<option value="">SELECIONAR</option>
<option *ngFor="let response of rating.responses" value="{{question.indicetpr}}">
{{response.desctpr}}
</option>
</select>
<div *ngIf="formRating.controls['indicetpr'].errors && (formRating.controls['indicetpr'].dirty
|| formRating.controls['indicetpr'].touched)" class="text text-danger">
Informe a sua avaliação.
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
rating-course.component.ts:
import { Component, OnInit, ViewChild, Inject, Input } from '@angular/core';
import {DialogService} from '../dialog.service';
import { SnackbarService } from '../snackbar.service';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { Rating } from '../objects/rating';
import {MessageService} from '../message.service';
import { FormBuilder, Validators, FormControl } from '@angular/forms';
@Component({
selector: 'app-rating-course',
templateUrl: './rating-course.component.html',
styleUrls: ['./rating-course.component.css']
})
export class RatingCourseComponent implements OnInit {
formRating;
_rating: Rating = new Rating();
_limit = 5;
_offset: number;
_formSubmited = false;
get rating(): Rating {
return this._rating;
}
set rating(value) {
this._rating = value;
}
get formSubmited(): boolean {
return this._formSubmited;
}
set formSubmited(value) {
this._formSubmited = value;
}
constructor(private _dialogService: DialogService,
public dialogRef: MatDialogRef<RatingCourseComponent>,
private snackbarService: SnackbarService,
private _messageService: MessageService,
private fb: FormBuilder,
@Inject(MAT_DIALOG_DATA) public data: any) { this._rating = data.rating }
ngOnInit() {
this._limit = 5;
this._offset = 0;
this.formRating = this.fb.group({
indicetpr: ['', [Validators.required]],
nomecur: [''],
cargahrcur: [''],
periodo: [''],
ptnegativoava: [''],
ptpositivoava: [''],
propostaava: ['']
})
}
closeModal() {
this._dialogService.closeDialog();
}
avaliarCriterio(question, response: number){
if(response != null && question != null) {
question.indicetpr = response;
}
}
salvar() {
const indicetprId: number = this.formRating.get(['indicetpr']).value;
console.log(indicetprId);
console.log(this.formRating);
if(this.formRating.invalid) {
console.log(indicetprId);
if(indicetprId === undefined || indicetprId === null) {
this.snackbarService.openSnackBar('Informe as respostas de todas as perguntas.', '');
this.formRating.get(['indicetpr']).status = 'INVALID';
this.formRating.get(['indicetpr']).errors = { required: true };
}
}
/*
for(let question of this._rating.questions) {
if(question.indicetpr === null) {
this.snackbarService.openSnackBar('Preencha todos os campos obrigatórios!', '')
}
}
*/
}
}
Может кто-нибудь мне помочь?