简体   繁体   English

Angular 错误:无法读取 null 的属性(读取“控件”)

[英]Angular Error: Cannot read properties of null (reading 'controls')

I'm very new to Angular and I am currently trying to understand how FormArrays, FormGroups and FormControls work.我对 Angular 非常陌生,我目前正在尝试了解 FormArrays、FormGroups 和 FormControls 的工作原理。 I want to insert data to my firebase collection in the format below.我想以下面的格式将数据插入到我的 firebase 集合中。

Firebase Format Firebase 格式

My code compiles successfully but I get an error in the console that says core.js:6486 ERROR TypeError: Cannot read properties of null (reading 'controls') at AddRecipeComponent_Template (add-recipe.component.html:56).我的代码编译成功,但我在控制台中收到一个错误,显示 core.js:6486 ERROR TypeError: Cannot read properties of null (reading 'controls') at AddRecipeComponent_Template (add-recipe.component.html:56)。 Is there something I am missing like initializations?有什么我缺少的东西,比如初始化吗?

my model looks like this: Recipe.ts我的 model 看起来像这样: Recipe.ts

export interface Recipe {
  id: string;
  metaData: {
    name: string;
    img: string;
    description: string;
    viewed: number;
  };
  recipeDetails: {
    ingredients: Ingredients[],
    instructions: string,
    cookingTime: string,
    servingPortion: string,
    dietaryInformation: string
  }
}

export interface Ingredients {
  name: string,
  amount: number,
  unit: string
}

export type RecommendedRecipe = { id: string } & Recipe['metaData'];
export type RecipeDetail = { id: string } & Recipe['metaData'] & Recipe['recipeDetails'];

add-recipe.component.html添加配方.component.html

<div class="container mb-5">
  <div class="row">

    <form [formGroup]="addRecipeForm" class="row g-3">

      <div formGroupName="metaData">

        <div class="col-md-6">
          <label for="name"> Recipe Name </label>
          <input type="text" name="name" class="form-control" formControlName="name" />
        </div>
        <div class="col-md-6">
          <label for="img"> Img </label>
          <input type="text" name="img" class="form-control" formControlName="img" />
        </div>
        <div class="col-md-6">
          <label for="description"> Description </label>
          <input type="text" name="description" class="form-control" formControlName="description" />
        </div>
        <div class="col-md-2">
          <input type="number" name="viewed" class="form-control" formControlName="viewed" value=1 hidden />
        </div>

      </div>

      <div formGroupName="recipeDetails">


        <div class="col-md-6">
          <label for="cookingTime"> Cooking Time </label>
          <input type="text" name="cookingTime" class="form-control" formControlName="cookingTime" />
        </div>
        <div class="col-md-6">
          <label for="servingPortion"> Serving Portion </label>
          <input type="text" name="servingPortion" class="form-control" formControlName="servingPortion" />
        </div>
        <div class="col-md-6">
          <label for="dietaryInformation"> Dietary Information </label>
          <input type="text" name="dietaryInformation" class="form-control" formControlName="dietaryInformation" />
        </div>
        <div class="col-md-6">
          <label for="instructions"> Instructions </label>
          <textarea class="form-control" name="instructions" rows="20" style="resize: none;"
            formControlName="instructions"></textarea>
        </div>

        <br/>

        <div class="col-md-2 d-md-flex justify-content-md-end">
          <button class="btn btn-primary" (click)="addIngredients()"> Add Ingredients </button>
        </div>

        <br/>

        <!--Ingredients-->
        <div formArrayName="ingredients" *ngFor="let ing of ingredients.controls; let i = index">

          <div [formGroupName]="i">
            <div class="col-md-2">
              <label for="name"> Ingredients Name </label>
              <input type="text" name="name" class="form-control" formControlName="name" />
            </div>
            <div class="col-md-2">
              <label for="amount"> Amount </label>
              <input type="number" name="amount" class="form-control" formControlName="amount" />
            </div>
            <div class="col-md-2">
              <label for="unit"> Unit </label>
              <select name="unit" class="form-control" formControlName="unit">
                <option value=""> Please Select Unit </option>
                <option *ngFor="let unitOpt of unitOptions" [value]="unitOpt">{{ unitOpt }}</option>
              </select>
            </div>
            <div class="col-md-6"></div>
            <div class="col-md-6"></div>
            <br />
          </div>

        </div>
      </div>


      <div class="col-md-6"></div>
      <div class="col-md-6"></div>

      <div class="col-md-2 gap-3 d-md-flex justify-content-md-end">
        <button class="btn btn-primary" (click)="addRecipe()"> Add Recipe </button>
        <a href="/recipe-list" class="btn btn-warning"> Cancel </a>
      </div>
    </form>
  </div>
</div>

add-recipe.component.ts添加配方.component.ts

import { Component, OnInit } from '@angular/core';
import { FormArray, FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { Recipe } from 'src/app/models/Recipe';
import { LoadingService } from 'src/app/services/loading.service';
import { RecipeService } from 'src/app/services/recipe.service';

@Component({
  selector: 'app-add-recipe',
  templateUrl: './add-recipe.component.html',
  styleUrls: ['./add-recipe.component.scss']
})
export class AddRecipeComponent implements OnInit {
  addRecipeForm: FormGroup;
  unitOptions: string[] = [
    'Piece(s)',
    'Slice(s)',
    'Liter(s)',
    'Milliliter(s)',
    'Gram(s)',
    'Kilogram(s)'
  ]

  constructor(
    private recipeService: RecipeService,
    private loadingService: LoadingService,
    private router: Router,
    private fb: FormBuilder
  ) {
    this.addRecipeForm = this.fb.group({
      metaData: this.fb.group({
        name: [''],
        img: [''],
        description: [''],
        viewed: ['']
      }),
      recipeDetails: this.fb.group({
        instructions: [''],
        cookingTime: [''],
        servingPortion: [''],
        dietaryInformation: [''],
        ingredients: this.fb.array([
          this.addIngredientsFormGroup()
        ],Validators.required)
      })   
    });
  }

  ngOnInit() {
  }

  public addIngredientsFormGroup(): FormGroup {
    return this.fb.group({
      name: [''],
      amount: [''],
      unit: ['']
    })
  }

  get ingredients():FormArray{
    return <FormArray> this.addRecipeForm.get('ingredients');
  }

  addIngredients() {
    this.ingredients.push(this.addIngredientsFormGroup());
  }

  public addRecipe(): void {
    // bind to Recipe Model
    var newRecipe = {
      metaData: this.addRecipeForm.value.metaData,
      recipeDetails: this.addRecipeForm.value.recipeDetails
    } as unknown as Recipe;

    console.log('addRecipeForm -> ', newRecipe);

    this.recipeService.createRecipe(newRecipe)
    .subscribe(
      (result) => {
        console.log("add result", result);
        this.router.navigateByUrl('/recipe-list');
      }
    );
  }

  onSubmit(): void {
    console.log(this.addRecipeForm);
  }

}

Your FormArray path in your getter is wrong, your formarray is inside recipeDetails formgroup, so that is where you need to point to:您的 getter 中的FormArray路径是错误的,您的 formarrayrecipeDetails formgroup 内,因此您需要指向:

get ingredients(): FormArray {
  return <FormArray>this.addRecipeForm.get('recipeDetails.ingredients');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法以 Angular 形式的嵌套形式读取 null 的属性(读取“控件”) - Cannot read properties of null (reading 'controls') in Nested Form of Angular Form Angular。 错误无法读取 null 的属性(读取“addFormGroup”) - Angular. Error Cannot read properties of null (reading 'addFormGroup') angular 错误类型错误:无法读取 null 的属性(读取“_rawValidators”) - angular ERROR TypeError: Cannot read properties of null (reading '_rawValidators') Angular:无法读取 null 的属性(读取“cannotContainSpace”) - Angular: Cannot read properties of null (reading 'cannotContainSpace') Angular 14:无法读取未定义的属性(读取“控件”) - Angular 14: Cannot read properties of undefined (reading 'controls') 类型错误:无法读取未定义的属性(读取“控件”)<jasmine> 在角度</jasmine> - TypeError: Cannot read properties of undefined (reading 'controls') at <Jasmine> in Angular VM500:1 错误类型错误:无法读取 Angular 15 上未定义的属性(读取“控件”) - VM500:1 ERROR TypeError: Cannot read properties of undefined (reading 'controls') on Angular 15 角度测试未捕获错误:未捕获(承诺):类型错误:无法读取 null 的属性(读取“参数”) - Angular Testing Uncaught Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'params') 如何通过热重载在本地使用 angular 库? [错误:无法读取 null 的属性(读取“firstCreatePass”)] - How to use angular library locally with hot reload? [Error: Cannot read properties of null (reading 'firstCreatePass')] 无法读取 null 的属性(读取“nativeElement”)- 测试 Angular - Cannot read properties of null (reading 'nativeElement') - Test Angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM