【发布时间】:2022-08-19 05:27:27
【问题描述】:
我有父表单“Quest”,包括一个子表单“Riddle”。
为了访问它,我使用注释 @ViewChild 如下:
quest.component.ts
export class CreateQuestComponent implements OnInit { @ViewChild(RiddleFormComponent, {static: true}) riddleForm!: RiddleFormComponent; minDate!: String; maxDate!: String; createQuestForm!: FormGroup; errorField=\"\"; constructor(private formBuilder: FormBuilder, private questService: QuestService, private authService: AuthService, private tokenStorage: TokenStorageService) { } ngOnInit(): void { const dtToday = new Date(); this.minDate = stringifyDate(dtToday.getFullYear(), (dtToday.getMonth() + 1), dtToday.getDate()); this.maxDate = stringifyDate((dtToday.getFullYear() + 1), (dtToday.getMonth() + 1), dtToday.getDate()); this.createQuestForm = this.formBuilder.group({ hunterFirstName: [\'\', [Validators.required, Validators.minLength(2)]], hunterLastName: [\'\', [Validators.required, Validators.minLength(2)]], hunterEmail: [\'\', [Validators.required, Validators.email]], launchDate: [\'\', [Validators.required, Validators.nullValidator]], penaltyTime: [\'\', [Validators.required, Validators.nullValidator]], participantsEmail: this.formBuilder.array([]), riddle: this.riddleForm.createGroup() }) } }这是我调用子表单时的 HTML 模板:
Quest.component.html
<form [formGroup]=\"createQuestForm\" class=\"primary-form\" (ngSubmit)=\"onSubmit()\" ngNativeValidate> . . . all inputs <app-riddle-form></app-riddle-form> </form>这是与 \'Rddle\' 组件相关的代码:
谜语form.component.ts
import {Component, OnInit} from \'@angular/core\'; import {FormBuilder, FormGroup, Validators} from \"@angular/forms\"; @Component({ selector: \'app-riddle-form\', templateUrl: \'./riddle-form.component.html\', //TODO add dynamic path styleUrls styleUrls: [\'../../quest/create-quest/create-quest.component.scss\', \'./riddle-form.component.scss\'], }) export class RiddleFormComponent implements OnInit { riddleFormGroup!: FormGroup; errorField = \"\"; constructor(private formBuilder: FormBuilder) { } ngOnInit(): void { } createGroup() { this.riddleFormGroup = this.formBuilder.group({ text: [\'\', [Validators.required, Validators.minLength(2)]], answer: [\'\', [Validators.required, Validators.minLength(2)]], }) return this.riddleFormGroup; } }谜语-form.component.html
<form [formGroup]=\"riddleFormGroup\" class=\"included-form\" ngNativeValidate> <div class=\"item\"> <textarea type=\"text\" name=\"text\" class=\"form-control\" [ngClass]=\"{\'border-red\': errorField==\'riddleText\'}\" formControlName=\"text\" placeholder=\"What is your riddle ?\" minlength=\"10\" required> </textarea> <input type=\"text\" class=\"form-control\" [ngClass]=\"{\'border-red\': errorField==\'riddleAnswer\'}\" name=\"answer\" placeholder=\"Answer\" formControlName=\"answer\" minlength=\"2\" maxlength=\"20\" required/> </div> </form>一切正常。 我可以从所有字段中获取提交的数据,甚至从 \'RiddleForm\'
问题是,当我提交表单时,除了嵌套表单 Riddle 之外的所有字段的验证工作正常,尽管在 \'riddle-form.component.ts\' 中设置了验证器:
-
嗯,你的代码有效吗?在 ngOnInit 中,riddleForm 应该为空
-
正如我所说,它有效。为什么它应该为空?
标签: angular