ОШИБКА Ошибка: не удается найти элемент управления с именем: ‘name’

#angular #typescript

#angular #машинописный текст

Вопрос:

После отправки формы, когда я возвращаюсь назад, я получаю сообщение об ошибке «Ошибка ошибки: не удается найти элемент управления с именем: ‘name'» . Есть ли что-то, чего мне не хватает? или мне нужно добавить еще несколько проверок?
это мой HTML-файл

 <div class="col-xs-12">
  <form [formGroup]="sectionForm" novalidate class="form">
    <div class="col-xs-12">
      <div class="col-sm-6">
        <fieldset class="form-group">
          <label>
            Section Name
          </label>
          <input type="text" formControlName="name" class="form-control">
          <div class="invalid-feedback" *ngIf="sectionForm.controls['name']?.errors amp;amp; submitted">
                        <span *ngIf="sectionForm.controls['name']?.errors.required">
                            Section name is required.
                        </span>
          </div>
        </fieldset>
        <fieldset class="form-group" *ngIf="!subject">
          <label>
            Choose a Subject
          </label>
          <select class="custom-select" placeholder="Select Subject" formControlName="subjectId" >
            <option *ngFor="let subject of subjects" [value]="subject._id">{{ subject?.name }}</option>
          </select>
          <div class="invalid-feedback" *ngIf="sectionForm.controls['subjectId'].errors amp;amp; submitted">
                    <span *ngIf="sectionForm.controls['subjectId'].errors.required">
                        Subject is required.
                    </span>
          </div>
        </fieldset>
        <button class="btn btn-primary" type="submit" (click)="create()">Submit</button>
      </div>
    </div>
  </form>
</div>
  

мой ts-файл

 export class SectionsCreateComponent implements OnInit {
  program;
  submitted;
  test;
  section;
  sectionForm: FormGroup =new FormGroup({});
  isBusy;
  chapter;
  subject;
  subjects = [];

  
  ngOnInit() {
    if (!this.program) {
      this.router.navigate(['program']);
    } else {
      this.refresh();
    }
  }

  refresh() {
    this.getSubjects();

    
    let testId=this.activatedRoute.snapshot.params['testId'];
    
    if (this.section) {
      this.sectionForm = this.fb.group({
        'name': [this.section.name, Validators.compose([Validators.required])],
        'testId': [testId, Validators.compose([Validators.required])],
        'subjectId': [this.section.subjectId, Validators.compose([Validators.required])]
      });
    } else {
      this.sectionForm = this.fb.group({
        'name': ['', Validators.compose([Validators.required])],
        'testId': [testId, Validators.compose([Validators.required])],
        'subjectId': [this.subject ? this.subject._id : '', Validators.compose([Validators.required])]
      });
    }
  }

  getSubjects() {
    this.subjectService.list(this.program).subscribe(
      data => this.subjects = data.data
    );
  }

  create() {
    this.submitted = true;

    if (!this.sectionForm.valid) {
      return;
    }
    let testId=this.activatedRoute.snapshot.params['testId'];
    let programId=this.program;

    this.isBusy = true;
    if (this.section amp;amp; this.section._id) {
      const reqObject = {
        ...this.sectionForm.value
      };
      reqObject._id = this.section._id;
      this.testsService.updateSection(reqObject).subscribe(
        data => {
          this.alertService.showSuccess('Success', 'Program updated successfully');
          this.dataService.setInterComponentsData({subject: this.subject, program: this.program, chapter: this.chapter, test: this.test});
          this.router.navigate([`tests/${testId}/${programId}/sections/list`]);
        }
      );
    } else {
      this.testsService.createSection(this.sectionForm.value).subscribe(
        data => {
          this.alertService.showSuccess('Success', 'Program added successfully');
          this.dataService.setInterComponentsData({subject: this.subject, program: this.program, chapter: this.chapter, test: this.test});
          this.router.navigate([`tests/${testId}/${programId}/sections/list`]);
        }
      );
    }
  }

}
  

Я также пытался

‘name’: [this.section this.section.имя ? this.section.имя: «, Validators.compose([Требуется Validators.required])],

Но получаю ошибки. Если я что-то упускаю, пожалуйста, помогите

Ответ №1:

Я вижу, что !this.program маршруты к другому компоненту к тому времени, когда вы извлекаете значение программы, вы, вероятно, отобразили форму с элементами управления form, которые изначально не определены, sectionForm: FormGroup =new FormGroup({});

Вы можете использовать *ngIf для условного отображения формы:

 <form *ngIf="program" [formGroup]="sectionForm" novalidate class="form">
 . . 
</form>
  

или создайте экземпляр FormGroup в ngOnInit:

 sectionForm: FormGroup;

ngOnInit(){

 this.sectionForm = this.fb.group({
    'name': ['', Validators.compose([Validators.required])],
    'testId': ['', Validators.compose([Validators.required])],
    'subjectId': ['', 
    Validators.compose([Validators.required])]
    });

    . . .

   }