没有 ControlContainer 的提供者和 ControlContainer 没有提供者

2023-11-22

我正在开发一个使用 Angular2 的应用程序。 我正在尝试在我的应用程序中使用反应式表单,但遇到了一些错误:

第一个错误是关于 NgControl 的,如下所示:

没有 NgControl 的提供者(“

div 类=“col-md-8” [错误->]输入类=“表单控制” id="产品名称ID" “):ProductEditComponent@16:24

第二个错误是关于ControlContainer的,如下:

没有 ControlContainer 的提供者(“ 分区 [错误 ->]div formArrayName="tags">

div 类=“行”>

按钮 cl"):

Htmm文件如下:

 <div class="panel panel-primary">
   <div class="panel-heading">
      {{pageTitle}}
</div>

<div class="panel-body">
    <form class="form-horizontal"
          novalidate
          (ngSubmit)="saveProduct()"
          formGroup="productForm" >
        <fieldset>
            <div class="form-group" 
                 [ngClass]="{'has-error': displayMessage.productName }">
                <label class="col-md-2 control-label" for="productNameId">Product Name</label>

                <div class="col-md-8">
                    <input class="form-control" 
                            id="productNameId" 
                            type="text" 
                            placeholder="Name (required)" 
                            formControlName="productName" />
                    <span class="help-block" *ngIf="displayMessage.productName">
                            {{displayMessage.productName}}
                    </span>
                </div>
            </div>


 <div formArrayName="tags">
                <div class="row">
                    <button class="col-md-offset-1 col-md-1 btn btn-default"
                            type="button"
                            (click)="addTag()">Add Tag
                    </button>
                </div>
                <div class="form-group"
                    *ngFor="let tag of tags.controls; let i=index" >
                    <label class="col-md-2 control-label" [attr.for]="i">Tag</label>

                    <div class="col-md-8">
                        <input class="form-control" 
                                [id]="i" 
                                type="text" 
                                placeholder="Tag" 
                                formControlName="i" />
                    </div>
                </div>
            </div>
    <!--more piece of code here -->

我的组件文件如下:

         import { Component, OnInit, AfterViewInit, OnDestroy, ViewChildren, ElementRef } from '@angular/core';
         import { FormBuilder, FormGroup, FormControl, FormArray, Validators, FormControlName,NgForm } from '@angular/forms';
         import { ActivatedRoute, Router  } from '@angular/router';

       import 'rxjs/add/operator/debounceTime';
       import 'rxjs/add/observable/fromEvent';
       import 'rxjs/add/observable/merge';
         import { Observable } from 'rxjs/Observable';
         import { Subscription } from 'rxjs/Subscription';

         import { IProduct } from './product';
         import { ProductService } from './product.service';

         import { NumberValidators } from '../shared/number.validator';
         import { GenericValidator } from '../shared/generic-validator';

  @Component({
      templateUrl: './product-edit.component.html'
   })
  export class ProductEditComponent implements OnInit, AfterViewInit, OnDestroy {
    @ViewChildren(FormControlName, { read: ElementRef }) formInputElements: ElementRef[];

pageTitle: string = 'Product Edit';
errorMessage: string;
productForm: FormGroup;

product: IProduct;
private sub: Subscription;

// Use with the generic validation message class
displayMessage: { [key: string]: string } = {};
private validationMessages: { [key: string]: { [key: string]: string } };
private genericValidator: GenericValidator;

get tags(): FormArray {
    return <FormArray>this.productForm.get('tags');
}

constructor(private fb: FormBuilder,
            private route: ActivatedRoute,
            private router: Router,
            private productService: ProductService) {

    // Defines all of the validation messages for the form.
    // These could instead be retrieved from a file or database.
    this.validationMessages = {
        productName: {
            required: 'Product name is required.',
            minlength: 'Product name must be at least three characters.',
            maxlength: 'Product name cannot exceed 50 characters.'
        },
        productCode: {
            required: 'Product code is required.'
        },
        starRating: {
            range: 'Rate the product between 1 (lowest) and 5 (highest).'
        }
    };

    // Define an instance of the validator for use with this form, 
    // passing in this form's set of validation messages.
    this.genericValidator = new GenericValidator(this.validationMessages);
}

ngOnInit(): void {
    this.productForm = this.fb.group({
        productName: ['', [Validators.required,
                           Validators.minLength(3),
                           Validators.maxLength(50)]],
        productCode: ['', Validators.required],
        starRating: ['', NumberValidators.range(1, 5)],
        tags: this.fb.array([]),
        description: ''
    });

    // Read the product Id from the route parameter
    this.sub = this.route.params.subscribe(
        params => {
            let id = +params['id'];
            this.getProduct(id);
        }
    );
}

ngOnDestroy(): void {
    this.sub.unsubscribe();
}

ngAfterViewInit(): void {
    // Watch for the blur event from any input element on the form.
    let controlBlurs: Observable<any>[] = this.formInputElements
        .map((formControl: ElementRef) => Observable.fromEvent(formControl.nativeElement, 'blur'));

    // Merge the blur event observable with the valueChanges observable
    Observable.merge(this.productForm.valueChanges, ...controlBlurs).debounceTime(800).subscribe(value => {
        this.displayMessage = this.genericValidator.processMessages(this.productForm);
    });
}

addTag(): void {
    this.tags.push(new FormControl());
}

getProduct(id: number): void {
    this.productService.getProduct(id)
        .subscribe(
            (product: IProduct) => this.onProductRetrieved(product),
            (error: any) => this.errorMessage = <any>error
        );
}

onProductRetrieved(product: IProduct): void {
    if (this.productForm) {
        this.productForm.reset();
    }
    this.product = product;

    if (this.product.id === 0) {
        this.pageTitle = 'Add Product';
    } else {
        this.pageTitle = `Edit Product: ${this.product.productName}`;
    }

    // Update the data on the form
    this.productForm.patchValue({
        productName: this.product.productName,
        productCode: this.product.productCode,
        starRating: this.product.starRating,
        description: this.product.description
    });
    this.productForm.setControl('tags', this.fb.array(this.product.tags || []));
}

deleteProduct(): void {
    if (this.product.id === 0) {
        // Don't delete, it was never saved.
        this.onSaveComplete();
   } else {
        if (confirm(`Really delete the product: ${this.product.productName}?`)) {
            this.productService.deleteProduct(this.product.id)
                .subscribe(
                    () => this.onSaveComplete(),
                    (error: any) => this.errorMessage = <any>error
                );
        }
    }
}

saveProduct(): void {
    if (this.productForm.dirty && this.productForm.valid) {
        // Copy the form values over the product object values
        let p = Object.assign({}, this.product, this.productForm.value);

        this.productService.saveProduct(p)
            .subscribe(
                () => this.onSaveComplete(),
                (error: any) => this.errorMessage = <any>error
            );
    } else if (!this.productForm.dirty) {
        this.onSaveComplete();
    }
}

onSaveComplete(): void {
    // Reset the form to clear the flags
    this.productForm.reset();
    this.router.navigate(['/products']);
   }
 }

我试图解决这个问题超过两天,但仍然没有解决方案。我在 stackoverflow 上看到了很多其他答案,但没有一个能解决我的问题。


从文件 app.module.ts 中的 @angular/forms 导入 Forms Module 和 ReactiveFormsModule

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

没有 ControlContainer 的提供者和 ControlContainer 没有提供者 的相关文章

  • 使用 JavaScript onclick 添加表格行

    我正在尝试使用 javascript 添加下面找到的完全相同的元素 我已经尝试了这里找到的所有解决方案 我什至尝试用php echo但没有运气 无需更改任何输入名称或类似内容 只需单击该按钮即可向表中添加另一行 仅此而已 这是该元素 tr
  • 无法重新加载/刷新活动路线

    我最近更新了新的 RC3 和 Router3alpha 似乎有些事情发生了变化 我注意到单击活动路径的链接不再导致组件重新加载 如何使用新的 router3 实现此行为 我的链接看起来像 a Link1 a 为了测试我只是在 ngOnIni
  • 占位符 HTML 元素?

    是否有任何 HTML 元素可以用来包装其他元素以用作占位符 例如 ul ul
  • 由于 MIME 类型不受支持,拒绝应用样式

    我不断收到一条错误消息 指出 MIME 类型 text html 不可执行或不是受支持的样式表 MIME 类型 并且启用了严格的 MIME 检查 我的链接代码是
  • Angular 2 中的变更检测

    我正在将角度 1 和角度 2 集成在一起 因此我有角度 1 控制器和服务以及角度 2 组件 这些对于数据检索和存储来说工作得很好 反之亦然 下面是我的 html 页面 h3 Angular 1 service h3 div div
  • 如何使用带有 python 的报告实验室将 html 文档转换为 pdf

    我正在尝试使用报告实验室将我创建的 html 文档转换为 pdf html 文档如下 我不确定如何做到这一点 我在网上查看过 似乎找不到解决方案 html文档 h2 Convert to pdf h2 p Lorem ipsum dolor
  • PyCharm 中有 HTML 块 {%%} 的快捷方式吗?

    我正在使用 HTML 块 例如 block content 经常使用 但必须输入括号和百分比符号很麻烦 有没有捷径或其他方法可以自动执行此操作 到目前为止我刚刚发现这个 PyCharm 中有插入 的快捷方式吗 https stackover
  • 使用 实现可访问性的更好做法是什么?

    我有一个下载链接 但我找不到任何良好的可访问解决方案来说明如何处理这种情况 我遵循一个共同的经验法则 按钮做事 链接去地方 我的情况是 我有一个触发文档下载的按钮 同一页面 我相信这应该是一个具有按钮角色的锚点 因为它明确不触发重定向或导航
  • 使用 Angular2 Router 发出 router.navigate 时出现无限重定向循环

    Note使用相关代码片段进行编辑 我遇到了一个奇怪的问题 在发出 router navigate 时 我进入了无限重定向循环 Setup 我使用哈希位置策略 并且该应用程序用作 Outlook 插件 I have three routing
  • tsconfig.json 中模块类型的区别

    在 tsconfig json 中 compilerOptions target es5 module commonjs moduleResolution node sourceMap true emitDecoratorMetadata
  • CSS 中的像素与像素密度

    我对 HTML 和 CSS 非常陌生 我突然想到 当决定某个东西是 5px 时 比如说 由于像素的物理尺寸取决于密度 所以 5px 在 100 ppi 的屏幕上看起来肯定比在 300 ppi 的屏幕上看起来更大ppi 这是正确的吗 如果是
  • 禁用引导列上的滚动

    我正在尝试禁用引导列上的滚动 这是我的代码 div class container fluid h 100 div class row h 100 div class col 4 h 100 bg dark fixed div div cl
  • 如何更改bootstrap中form-control弹出窗口中必填字段的默认消息?

  • 如何将 Google Charts 与 Vue.js 库一起使用?

    我正在尝试使用 Vue js 库使用 Google Charts 制作图表 但我不知道如何添加到 div 这是我尝试做的 这是如何使用普通 javascript 添加图表 这是文档的代码示例 https developers google
  • MVC 在布局代码之前执行视图代码并破坏我的脚本顺序

    我正在尝试将所有 javascript 包含内容移至页面底部 我正在将 MVC 与 Razor 一起使用 我编写了一个辅助方法来注册脚本 它按注册顺序保留脚本 并排除重复的内容 Html RegisterScript scripts som
  • 表单计算器脚本基本价格未加载 OnLoad

    我的表单中有一个计算器来计算我的下拉选项选择 function select calculate on change calc input type checkbox calculate on click calc function cal
  • FireFox 中的自动滚动

    我的应用程序是实时聊天 我有一个 Div 来包装消息 每条消息都是一个 div 所以 在几条消息之后 我的 DOM 看起来像这样 div div Message number two div div div div
  • 为什么我不能在 AngularJS 中使用 data-* 作为指令的属性名称?

    On the t他的笨蛋 http plnkr co edit l3KoY3 p preview您可以注意到属性名称模式的奇怪行为data 在指令中 电话 Test of data named attribute br
  • Angular 2获取元素高度

    我这里有一个非常简单的例子 它只是一个带有单个 div 的角度应用程序 是否可以获取div的角度高度 我想我可以用 ViewChild 和 offsetHeight 来做到这一点 import Component ElementRef Vi
  • 如何获取浏览器视口中当前显示的内容

    如何获取当前正在显示长文档的哪一部分的指示 例如 如果我的 html 包含 1 000 行 1 2 3 9991000 并且用户位于显示第 500 行的中间附近 那么我想得到 500 n501 n502 或类似的内容 显然 大多数场景都会比

随机推荐

  • 将范围变量连接到角度指令表达式中的字符串中

    我在 Angular ng click 指令中使用作用域方法 如下所示 a obj val1 obj val2 a 这里的问题是 obj val1 和 obj val2 被解释为传递给表达式中的方法的字符串的一部分 我需要将它们作为变量进行
  • Java方法使用反射分配对象字段值

    我想知道 Java 中是否可以有类似下面的内容 public class MyClass private String name private Integer age private Date dateOfBirth constructo
  • 如何自动回答 y(kill-matching-buffers 询问我是否应该终止修改的缓冲区)?

    在 Emacs 中 如何杀死与正则表达式匹配的缓冲区 Edit 我该如何回答y自动地 kill matching buffers询问我是否应该杀死修改过的缓冲区 像这样的东西吗 defun bk kill buffers bfrRgxp i
  • 使用 React Router 进行条件渲染

    我想在顶部渲染一些带有导航的路线 而在没有任何导航的情况下渲染其他路线 如注册 登录页面 对于导航的设置 我有 const App gt
  • 从类路径中的任何位置加载资源

    我有一个简单的 java 应用程序 它从当前包加载属性文件 this getClass getResourceAsStream props properties 当我想要的属性文件位于当前包中时 这可以正常工作 但是 我想将此应用程序打包为
  • 素数生成器解释? [复制]

    这个问题在这里已经有答案了 我正在寻找一种生成素数的算法 我找到了罗伯特 威廉 汉克斯 Robert William Hanks 创作的以下一幅作品 它非常有效并且比其他算法更好 但我无法理解其背后的数学原理 def primes n Re
  • 将数组传递给 Java 方法

    如何将整个数组传递给方法 private void PassArray String arrayw new String 4 populate array PrintA arrayw private void PrintA String a
  • Java:具有接口属性的对象的 Jackson 多态 JSON 反序列化?

    我正在使用杰克逊的ObjectMapper反序列化包含接口作为其属性之一的对象的 JSON 表示形式 代码的简化版本可以在这里看到 https gist github com sscovil 8735923 基本上 我有一个班级Asset有
  • ViewPager 和 FragmentPagerAdapter 中 Fragment 的 Android 生命周期管理

    我一直在努力找出如何正确管理 Fragment 中的内容FragmentActivity with a ViewPager是 在详细介绍之前 我先对我面临的问题进行快速总结如下 我有一个FragmentActivity with a Vie
  • Android Studio 2.1 将字节码转换为 dex 时出错

    自从我将 android studio 从 2 0 更新到 2 1 后 我收到以下错误 错误 将字节码转换为 dex 时出错 原因 Dex 无法解析版本 52 字节代码 这是由于 使用 Java 8 或更高版本编译的库依赖项 如果 您正在库
  • 使用 Visual Studio 2015 编译 ToolsVersion 12

    我安装了一台新电脑并安装了VS2015 编译我当前正在处理的项目会产生一些无效代码 ILSpy 创建无法编译的源代码 使用 ToolsVersion 12 在 VS2013 中运行良好 日志文件告诉我 ToolsVersion 12 丢失
  • ExtJs4 - 与网格 ColumnModel 等效的是什么?

    ExtJs3相当于什么Ext grid ColumnModel在 ExtJs4 中 我想做的是隐藏一列 我在 ExtJs3 中做了如下操作 grid colModel setHidden 1 true 您可以使用 Ext grid colu
  • 查找非有限值的最快方法

    这是受到以下启发 python numpy 中的组合掩码 任务是创建一个包含所有非有限值的布尔数组 例如 gt gt gt arr np array 0 2 np inf np inf np nan gt gt gt np isfinite
  • 使用 EventTrigger 设置属性

    我希望能够使用 EventTrigger 设置属性 但这有很多问题 1 EventTriggers仅支持Actions 所以我必须使用storyBoard来设置我的属性 2 一旦我使用故事板 我有两个选择 停止 动画停止后 值将恢复到动画开
  • git log -L 不带差异

    我正在尝试使用git log L
  • 使用 Ruby 进行科学编程

    我正在使用 python 或 Octave 进行数学计算 因为手头有非常好的函数和库 但最近我对 Ruby 产生了兴趣 我想知道 Ruby 中是否有相当于 Python 中的 numpy scipy 的科学编程工具 具体来说 我正在寻找一些
  • 选择页面上的所有元素[关闭]

    很难说出这里问的是什么 这个问题模棱两可 含糊不清 不完整 过于宽泛或言辞激烈 无法以目前的形式合理回答 如需帮助澄清此问题以便重新打开 访问帮助中心 我正在寻找 javascript 中的一个函数 它可以单击我页面上的每个元素 链接 按钮
  • 将指针传递给结构数组时出错

    include
  • Bootstrap 多选不起作用

    我正在尝试使用多选 Bootstrap 我使用了以下代码 该代码也可以在他们的网站上找到 http davidstutz github io bootstrap multiselect 它显示了多选按钮 并且由于我已经选择了 奶酪和意大利辣
  • 没有 ControlContainer 的提供者和 ControlContainer 没有提供者

    我正在开发一个使用 Angular2 的应用程序 我正在尝试在我的应用程序中使用反应式表单 但遇到了一些错误 第一个错误是关于 NgControl 的 如下所示 没有 NgControl 的提供者 div 类 col md 8 错误 gt