【问题标题】:Property 'form' has no initializer and is not definitely assigned in the constructor属性 'form' 没有初始化程序,也没有在构造函数中明确分配
【发布时间】:2021-04-13 10:54:57
【问题描述】:

这是我的 component.ts:

import { Component, OnInit } from '@angular/core';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-microplate',
  templateUrl: './microplate.component.html',
  styleUrls: ['./microplate.component.css']
})
export class MicroplateComponent implements OnInit {
  form: FormGroup;

  ngOnInit(): void {
    this.form = new FormGroup({
      columns: new FormControl('some value', [
        Validators.required
      ])
    });
  }

  get columns() { return this.form.get('columns'); }
}

这是我的component.html:

<form [formGroup]="form">
    <label for="columns"><b>Columns: </b></label>
    <input id="columns" type="text" [formControlName]="columns">
</form>

我在form: FormGroup; 收到以下错误消息:

Property 'form' has no initializer and is not definitely assigned in the constructor.

我使用了来自 Angular 网站的信息,但我无法解决问题。任何帮助将不胜感激。

【问题讨论】:

  • 使用&lt;form *ngIf="form" [formGroup]="form"&gt;。原因是您在 ngOnInit 中创建了表单,直到尚未定义表单。此外是formControlName="columns" - 没有[ ]
  • @Eliseo,我照你说的做了,但还是同样的错误信息。
  • 那么我应该认为问题出在您的get columns 上。试试get columns(){ return this.form?this.form.get('columns'):null}。注意我只是做了一个stackblitz,它不需要
    。堆栈闪电战:stackblitz.com/edit/…
  • @Eliseo,我做了你所说的新更改,现在我收到错误消息Type 'AbstractControl | null' is not assignable to type 'string | number | null'.
  • Mohsen,你删除了formControlName 中的[] 吗?如果您使用[] Angular,请将“列”视为变量,并且由于您有一个变量(实际上是一个 getter,它在您的代码中是不必要的)是一个 FormControl 而不是一个字符串 Angular 失败。

标签: javascript angular


【解决方案1】:

魔神使用的理由

get columns() { return this.form.get('columns'); }

是为了做类似的事情

    <form [formGroup]="form">
        <label for="columns"><b>Columns: </b></label>
        <!--see that you use formControlName="columns", not between []-->
        <!--you can also use
           <input id="columns" type="text" [formControlName]="'columns'">
            see that in this case is an string, NOT the variable "columns" -->
        <input id="columns" type="text" formControlName="columns">
        <!--here use "columns" that is your FormControl to ask if you has errors and is touched-->
        <div  *ngIf="columns.errors && columns.touched">Required</div>
    </form>

【讨论】:

    猜你喜欢
    • 2021-05-21
    • 2021-05-06
    • 2021-08-14
    • 2021-02-28
    • 2021-12-25
    相关资源
    最近更新 更多