typescript 角度:找不到名称为“日期”的控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51214852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:31:09  来源:igfitidea点击:

Angular: Cannot find control with name: 'date'

javascripthtmlangulartypescript

提问by The Dead Man

I am creating a form where a user select date and fill the form and subimit the form, here is what I have . for reference I am using igx-calendar

我正在创建一个表单,其中用户选择日期并填写表单并提交表单,这是我所拥有的。作为参考,我正在使用 igx-calendar

calendar component.ts:

日历组件.ts:

import { Component, OnInit, forwardRef, Input, ElementRef, ViewChild } from '@angular/core';
import { IgxCalendarComponent, IgxDialogComponent } from 'igniteui-angular';
import {  NgModel, FormControl, ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
@Component({
  selector: 'app-calendar',
  templateUrl: './calendar.component.html',
  styleUrls: ['./calendar.component.scss'],
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CalendarComponent), multi: true }
  ]
})
export class CalendarComponent implements ControlValueAccessor, OnInit {
  @ViewChild('calendar') public calendar: IgxCalendarComponent;
  @ViewChild('alert') public dialog: IgxDialogComponent;
  @Input()
  label: string;


  private _theDate: string;

  constructor() { }

  propagateChange = (_: any) => { };
  onTouched: any = () => { };

  writeValue(obj: any): void {
    console.log('writeValue => obj : ', obj);
    if (obj) {
      this._theDate = obj;
    }
  }

  registerOnChange(fn: any): void {
    this.propagateChange = fn;
    console.log('registerOnChange => fn : ', fn);
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
    console.log('registerOnTouched => fn : ', fn);
  }

  get theDate() {
    console.log('get theDate()');
    return this._theDate;
  }

  set theDate(val) {
    console.log('set theDate(val) - val => ', val);
    this._theDate = val;
    this.propagateChange(val);
  }
  public verifyRange(dates: Date[]) {
    if (dates.length > 5) {
      this.calendar.selectDate(dates[0]);
      this.dialog.open();
    }
  }
  ngOnInit() {

  }
}

calender.html

日历.html

<div class="sample-wrapper">
    <div class="sample-content">
        <!-- Single selection mode -->
        <article class="sample-column calendar-wrapper">
            <igx-calendar></igx-calendar>
        </article>

    </div>
</div>

Booking.component.ts UPDATE

Booking.component.ts更新

export class BookingComponent implements OnInit {

  comments: {};
  addcomments: Comment[];
  angForm: FormGroup;
  // tslint:disable-next-line:max-line-length
  validEmail = false;

  constructor(private flashMessages: FlashMessagesService,
    private fb: FormBuilder,
    private activeRouter: ActivatedRoute,
    private moviesService: MoviesService) {
    this.comments = [];
    this.createForm();
    }
  onChange(newValue) {
    // tslint:disable-next-line:max-line-length
    const validEmail = /^(([^<>()\[\]\.,;:\s@"]+(\.[^<>()\[\]\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (validEmail.test(newValue)) {
      this.validEmail = true;
    } else {
      this.validEmail = false;
    }

  }

  createForm() {
    this.angForm = this.fb.group({
      email: new FormControl('', [Validators.required, Validators.email])
    });
  }
  addReview(date, email, city, hotel) {
    this.moviesService.addReview(date, email, city, hotel).subscribe(success => {
      this.flashMessages.show('You are data we succesfully submitted', { cssClass: 'alert-success', timeout: 3000 });
      // get the id
      this.activeRouter.params.subscribe((params) => {
        // tslint:disable-next-line:prefer-const
        let id = params['id'];
        this.moviesService.getComments(id)
          .subscribe(comments => {
            console.log(comments);
            this.comments = comments;
          });
      });
    }, error => {
      this.flashMessages.show('Something went wrong', { cssClass: 'alert-danger', timeout: 3000 });
    });
  }
  ngOnInit() {

  }

}

Booking.component.html

预订.component.html

<div class="row about-booking">
    <flash-messages></flash-messages>
    <form [formGroup]="angForm" class="form-element">
      <div class="col-sm-4 offset-sm-2 about-booking_calendar">
        <div class="form-group form-element_date">
          <app-calendar formControlName="date" [(ngModel)]="theDate" #date></app-calendar> 
        </div>
      </div>
      <div class="col-sm-4 about-booking_form">
        <div class="form-group form-element_email">
          <input type="email" class="form-control info" placeholder="Email" formControlName="email" #email (ngModelChange)="onChange($event)">
        </div>
        <div *ngIf="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)"
          class="alert alert-danger">
          <div *ngIf="angForm.controls['email'].errors.required">
            Email is required.
          </div>
        </div>
        <div class="input-group mb-3 form-element_city">
          <select class="custom-select" id="inputGroupSelect01" #cityName>
            <option selected *ngFor="let city of cities" [ngValue]="city.name">{{city.name}}</option>

          </select>
        </div>
        <div class="input-group mb-3 form-element_hotel">
          <select class="custom-select" id="inputGroupSelect01" #hotelName>
            <option selected *ngFor="let hotel of hotels" [ngValue]="hotel.name">{{hotel.name}}</option>

          </select>
        </div>
        <div class="form-group">
          <button type="submit" (click)="addReview(date.value, email.value, cityName.value , hotelName.value)" class="btn btn-primary btn-block form-element_btn"
            [disabled]="!validEmail">Book</button>
        </div>
      </div>
    </form>
  </div>

when I submit the data I get the following error:

当我提交数据时,出现以下错误:

BookingComponent.html:59 ERROR Error: Cannot find control with name: 'date'

BookingComponent.html:59 错误错误:找不到名称为“日期”的控件

what is wrong with my code?

我的代码有什么问题?

回答by pogiaron

in your createForm() function you didn't added the date FormControl

在您的 createForm() 函数中,您没有添加日期 FormControl

createForm() {
  this.angForm = this.fb.group({
    email: new FormControl('', [Validators.required, Validators.email]),
    date: new FormControl('') // this line missing in your code
  });
}

you shouldn't use both ngModel (template driven forms) and formControlName (reactive forms) in the same input.

您不应在同一输入中同时使用 ngModel(模板驱动表单)和 formControlName(反应表单)。

回答by Abdeali Chandanwala

In my case I was getting this same error for all the fields in the FormGroup, the reason was the data from server was NOTreceived and the html UI code attempted to executed the reactive form and hence the error. So to solve this issue I had to use the *ngIf condition on the form element and stopped the rendering of the form until the server response was completed.

在我的情况下,我在 FormGroup 中的所有字段都遇到了同样的错误,原因是没有收到来自服务器的数据,并且 html UI 代码尝试执行响应式表单,因此出现错误。所以为了解决这个问题,我不得不在表单元素上使用 *ngIf 条件并停止表单的呈现,直到服务器响应完成。

<form [formGroup]="profileForm" (ngSubmit)="onSubmit()" *ngIf="userProfile != undefined">