import { ChangeDetectionStrategy, Component, effect, input, OnInit, output, signal } from '@angular/core'; import { form, FormField } from '@angular/forms/signals'; import { Answer, AnswerDto, Question } from '../survey.models'; type SurveyAnswerForm = { answer_id: string; text: string; }; @Component({ selector: 'app-survey-question', templateUrl: './survey-question.component.html', styleUrls: ['./survey-question.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [FormField], }) export class SurveyQuestionComponent implements OnInit { answer = output(); question = input.required(); questionIdx = input(0); firstAnswer!: Answer; answerModel = signal({ answer_id: '', text: '' }); answerForm = form(this.answerModel); private initialized = false; private syncAnswer = effect(() => { if (!this.initialized) return; const answer = this.answerModel(); if (!answer.answer_id) return; const text = answer.text?.trim() ?? ''; this.answer.emit({ answer_id: Number(answer.answer_id), ...(text && { text }), }); }); ngOnInit(): void { const [firstAnswer] = this.question().answers; this.firstAnswer = firstAnswer; if (this.question().answers.length === 1 && firstAnswer.open) { this.answerModel.set({ answer_id: firstAnswer.answer_id.toString(), text: '' }); } this.initialized = true; } }