Я только что заметил странное поведение диалога подтверждения PrimeNG. В test.component.html есть поле ввода. Он проверяет, является ли введенное значение больше 150. Если оно больше, то под полем ввода отображается кнопка подтверждения («Пожалуйста, подтвердите»). Нажав на нее, вы увидите диалог с Да и Нет.
Кнопка подтверждения исчезнет после выбора либо Да, либо Нет.
Теперь вот проблема:
Исчезновение работает только в том случае, если метод подтверждения вызывается непосредственно в test.component.ts. Я хотел бы извлечь его в службу (customConfirmation.service.ts), но исчезновение там не работает. Ты знаешь почему? Я понятия не имею. («this.messagesWeightTest» и кнопка исчезновения не работают.)
test.component.html
<div class="p-col-12 p-md-6 p-lg-5">
Weight:
<div class="ui-inputgroup">
<input pInputText type="number" id="weight" name="weight" [(ngModel)]="newTest.testWeight"
placeholder="---">
<span class="ui-inputgroup-addon">kg</span>
</div>
<div *ngIf="validateIfWeightOutsideRange()">
<div>
<p-confirmDialog key="confirmWeightTest"></p-confirmDialog>
<button type="button" (click)="confirmWeightTest()" pButton icon="pi pi-check"
label="Please confirm!">
</button>
<p-messages [value]="messagesWeightTest"></p-messages>
</div>
</div>
</div>
Кажется, что все "принять" и "отклонить" не работают:
customConfirmation.service.ts
import {Injectable} from '@angular/core';
import {SessionService} from "./session.service";
import {ConfirmationService, Message} from "primeng/api";
@Injectable()
export class CustomConfirmationService {
messagesWeightTest: Message[] = [];
weightConfirmed: boolean = false;
constructor(private confirmationService: ConfirmationService) {}
confirmWeightTest() {
this.confirmationService.confirm({
message: 'Are you sure?',
header: 'Confirmation',
icon: 'pi pi-exclamation-triangle',
key: 'confirmWeightTest',
accept: () => {
this.messagesWeightTest = [{
severity: 'info', summary: 'Confirmed', detail: 'The input is correct.'}];
this.weightConfirmed = true;
},
reject: () => {
this.sessionService.newTest.testWeight = null;
this.weightConfirmed = true;
}
});
}
}
test.component.ts просто вызывает метод подтверждения из сервиса:
test.component.ts
import {Component, Injectable, Input, OnInit} from '@angular/core';
import {ConfirmationService, Message, SelectItem} from "primeng/api";
import {trigger, state, style, transition, animate} from '@angular/animations';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {CustomConfirmationService} from "../services/customConfirmation.service";
import {ValidationService} from "../services/validation.service";
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
@Injectable()
export class TestComponent implements OnInit {
constructor(private fb: FormBuilder,
private customConfirmationService: CustomConfirmationService,
private confirmationService: ConfirmationService,
private validationService: ValidationService) {
}
ngOnInit() {}
// Confirmations for ConfirmDialogs
confirmWeightTest() {
this.customConfirmationService.confirmWeightTest();
}
// Validations for ConfirmDialogs --> work!
validateIfWeightOutsideRange() {
return !!this.validationService.validateIfWeightOutsideRange();
}
Опять же, если я скопирую и вставлю Подтверждение WeightTest () из customConfirmation.service.ts в test.component.ts, все будет работать нормально. Я также проверил это с другим проектом.
Я был бы рад, если бы вы могли рассказать мне, что здесь происходит.
Пожалуйста, обратитесь к Диалог подтверждения Prime-NG: Скрыть кнопку после подтверждения
Я реализовал все как рекомендовано в ответе на этот вопрос. Спасибо!