Error ng0201 no provider for ngcontrol found in nodeinjector

Issue I have run out of ideas. I want to use [(ngModel)] in my inputs in a component of an...

Issue

I have run out of ideas. I want to use [(ngModel)] in my inputs in a component of an angular library so I need to import FormsModule in the library’s module to use it. I did it. I have a demo project where I call a component of this library to test it but I get the error in the title. Someone knows what to do?

I tried also in a component in the demo angular project importing FormsModule in app.module and it works. But it is imposible to achieve in the component of the library.

Error:

core.js:6162 ERROR Error: NG0201: No provider for NgControl found in NodeInjector. Find more at https://angular.io/errors/NG0201
    at throwProviderNotFoundError (core.js:233)
    at notFoundValueOrThrow (core.js:3316)
    at lookupTokenUsingModuleInjector (core.js:3351)
    at getOrCreateInjectable (core.js:3453)
    at Module.ɵɵdirectiveInject (core.js:14634)
    at NodeInjectorFactory.NgControlStatus_Factory [as factory] (forms.js:1301)
    at getNodeInjectable (core.js:3548)
    at instantiateAllDirectives (core.js:10227)
    at createDirectivesInstances (core.js:9576)
    at Module.ɵɵelementStart (core.js:14778)

Has someone any ideas? Thanks in advance.

library´s .module file:

import { NgModule } from '@angular/core';
import { SavingGoalComponent } from './saving-goal/saving-goal.component';
import { EarlyRetirementComponent } from './early-retirement/early-retirement.component';
import { SavingsDurationComponent } from './savings-duration/savings-duration.component';
import { MatSliderModule } from '@angular/material/slider';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';
import { CommonModule } from '@angular/common';
import { TranslateModule } from '@ngx-translate/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  declarations: [
    SavingGoalComponent,
    EarlyRetirementComponent,
    SavingsDurationComponent
  ],
  imports: [
    CommonModule,
    BrowserModule,
    TranslateModule,
    MatSliderModule,
    MatSelectModule,
    MatFormFieldModule,
    FormsModule
  ],
  exports: [
    SavingGoalComponent,
    EarlyRetirementComponent,
    SavingsDurationComponent
  ],
})
export class CalculatorsLibraryModule { }

project.ts file:

/*
 * Public API Surface of calculators-library
 */

export * from './lib/calculators-library.module';

export { SavingGoalComponent } from './lib/saving-goal/saving-goal.component';
export { EarlyRetirementComponent } from './lib/early-retirement/early-retirement.component';
export { SavingsDurationComponent } from './lib/savings-duration/savings-duration.component';

app.module of demo angular project:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CalculatorsLibraryModule } from '../../../calculators-library/src/project';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (http: HttpClient) => {
          return new TranslateHttpLoader(
            http,
            '../../assets/i18n/'
          );
        },
        deps: [HttpClient]
      },
      defaultLanguage: 'es'
    }),
    AppRoutingModule,
    CalculatorsLibraryModule,
    BrowserAnimationsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})`enter code here`
export class AppModule { }

app.component of demo project:

<div class="calculator">
    <lib-early-retirement></lib-early-retirement>
</div>

lib component.html:

<div class="module-column">
                <label for="erc-age">Tu edad actual es</label>
                <input id="erc-age" name="erc-age" type="text" [(ngModel)]="inputs.Age">
                <mat-slider [(ngModel)]="inputs.Age" [min]="0" [max]="100"></mat-slider>
            </div>

Solution

I found the error. I named an atributte in another component with the same name that it is used by a directive in ReactiveForms. It seems like when I import FormsModule, the error appears and not before this action, so I needed to import ReactiveForms too to solve the problem.
In my case, I do not need ReactiveForms, so removing the atributte from the other component and renaming it solve the problem and now everything works fine.

#angular #typescript #web-applications

#angular #typescript #веб-приложения

Вопрос:

у меня полностью закончились идеи. Я хочу использовать модуль реактивных форм, поэтому я импортировал его в app.module.ts, например

 import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    ...
    ReactiveFormsModule,
    ...
  ],
  providers: [],
  bootstrap: [AppComponent]
})
 

В моем компоненте я определил:

 import { Component, OnInit} from "@angular/core";

import { FormControl, FormGroup } from '@angular/forms';

@Component({
    ...
})

export class SearchComponent implements OnInit{
    //Variablen
    form: FormGroup;
    
    //Konstruktor
    constructor(){}

    //Methoden
    ngOnInit(){
        this.form = new FormGroup({
            'title': new FormControl(null)
        });
    }

    showValue(){
        console.log(this.form.get('title'));
    }
}
 

Компиляция работает хорошо, но при ее отображении происходит сбой с ошибкой, показанной ниже в консоли браузера:
«Ошибка core.js: ОШИБКА 6156: NG0201: в NodeInjector не найден поставщик для ngControl».

У кого-нибудь из вас есть идея, что пошло не так?

Я был бы очень признателен за любую подсказку.

Большое спасибо!

Комментарии:

1. Насколько я знаю, это не рекомендуется использовать new FormGroup(...) . Введите экземпляр FormBuilder и, чем использовать this.fb.group({ control: new FormControl(null)}) . Возможно, это может вам помочь.

Ответ №1:

Чтобы выполнить эту работу, вам нужно будет импортировать ReactiveFormsModule в ваш @NgModule, который является ViewsModule, как следует из вашего вопроса. Поскольку FormControl отображается как часть ReactiveFormsModule, а НЕ FormsModule.

 import { ReactiveFormsModule, ... } from '@angular/forms';

@NgModule({
  imports: [..., ReactiveFormsModule, ...],
  ...
})
export class ViewsModule {...}
 

Ответ №2:

Только что нашел мою (ту же) ошибку, вам нужно импортировать ReactiveFormsModule в «локальный» модуль… В вашем случае это должно быть «search-component.module.ts»

Ответ №3:

импортируйте FormsModule также в app.module.ts

Комментарии:

1. Я попробовал, но проблема не решена. Я использую Angular Cli 11.1.1. В аналогичном проекте я использую 9.1.12, и все работает нормально. Может быть, это проблема с новой версией?

2. Это проблема с импортом. Ваш SearchComponent не объявлен в app.module.ts. import FormsModule и ReactiveFormsModule, где вы объявили свой SearchComponent.

3. Его нет в списке выше, вы правы, но там объявлен SeachComponent, представленный … . Проблема в том, что объявление и инициализация форм не находят formControlName . Если я оставлю его без имени, он выдает ошибку, но работает. Если я попытаюсь установить formControlName=»title» в HTML, произойдет сбой с кодом ошибки, указанным в названии этого сообщения

Ответ №4:

Вы можете попробовать добавить *ngIf=»!isLoading» в свой контейнер формы в html. В файле de .ts добавьте isLoading = true; в верхней части объявлений var, а затем, после создания вашей формы, isLoading = false; С уважением.

Ответ №5:

Импорт ReactiveFormsModule также в текущем примере модуля ( login.module.ts или любом другом модуле), а не в app.module.ts :

введите описание изображения здесь

Ответ №6:

поместите его в свой локальный модуль.

 import { FormsModule } from '@angular/forms';
@NgModule({
  declarations: [],
  imports: [
    FormsModule
  ]
})
export class ... {} 

To make this work you’ll have to import the ReactiveFormsModule in your @NgModule which is the ViewsModule as your question suggests. As FormControl is exposed as a part of ReactiveFormsModule and NOT the FormsModule.

import { ReactiveFormsModule, ... } from '@angular/forms';@NgModule({  imports: [..., ReactiveFormsModule, ...],  ...})export class ViewsModule {...}

Just found my (same) mistake, you have to import ReactiveFormsModule in «local» module…In your case it must be «search-component.module.ts»


import FormsModule as well in app.module.ts


writelines

Guest


  • #1

writelines Asks: ERROR Error: NG0201: No provider for NgControl found in NodeInjector
i ran completly out of ideas. I want to user Reactive Forms Module, so i imported it in app.module.ts like

Code:

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    ...
    ReactiveFormsModule,
    ...
  ],
  providers: [],
  bootstrap: [AppComponent]
})

In my Component i defined:

Code:

import { Component, OnInit} from "@angular/core";

import { FormControl, FormGroup } from '@angular/forms';

@Component({
    ...
})

export class SearchComponent implements OnInit{
    //Variablen
    form: FormGroup;
    
    //Konstruktor
    constructor(){}

    //Methoden
    ngOnInit(){
        this.form = new FormGroup({
            'title': new FormControl(null)
        });
    }

    showValue(){
        console.log(this.form.get('title'));
    }
}

Compiling works well, but when displaying it it crashes with the error below shown in the Browser Console: «core.js:6156 ERROR Error: NG0201: No provider for NgControl found in NodeInjector.»

Does anybody of you has an idea what went wrong?

I would really appreciate any hint.

Thanks a lot!

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, solveforum.

  • ROHIT HARI
  • 23 minutes ago
  • Geography
  • Replies: 0

ROHIT HARI Asks: Loop clipping image by featurecollections of a vector in Earth Engine and exporting all TIFF
Below is my code. When I run this code I get the error:

Line 27: data.map is not a function

Code:

var data =ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
                  .filterDate('2022-01-01', '2022-12-30')
                  // Pre-filter to get less cloudy granules.
                  .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',20))
                  .select('B4', 'B3', 'B2', 'B8')
                  .mean()
                  ;
print(data)

//Map.addLayer(data,{min:0,max:3000, bands:['B4', 'B3', 'B2']},'layer')
var aoi= ee.FeatureCollection(table2).geometry();
var attribute = 'id'


var loop = function(image){
 var output = aoi.map(function(geom){
   var name = geom.get(attribute)
   var clip= image.clip(geom);
   var finalname = ee.String(name)
   return clip.set('name', finalname).set('system:footprint', geom);
  })
  return output
};
print(loop)
var outputd = data.map(loop).flatten()
var size = outputd.size().getInfo();
var outputlist = outputd.toList(size);

for (var i=0; i<size; i++) {
  var image = ee.Image(outputlist.get(i));
  var name = image.get('name').getInfo();
  Export.image.toDrive({
    image:image, 
    description:name, 
    folder: 'FOLDER', 
    fileNamePrefix: name, 
    region: image.aoi().getInfo(), 
    scale:10
  })
}

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, solveforum.

  • MJM
  • 23 minutes ago
  • Geography
  • Replies: 0

MJM Asks: Iterating SAGA Split Features Layer tool across files in directory using python
I have a few thousand polygon shapefiles in a folder that I would like the SAGA Split Features Layer tool to perform its operation on. The operation and parameters are the same for every polygon, but just can’t get it to iterate across the files. Below is the result I want.

enter image description here

====>
enter image description here

Code:

# split twp grids into 4
from qgis.core import QgsProcessingAlgorithm
import glob
import os

inpath = "C:\GIS Data\ab_grids\twp_polygons"
outpath = "C:\GIS Data\ab_grids\twp2_2"

input_files = glob.glob(os.path.join(inpath, "*.shp"))

for input_file in input_files:

    output_file = os.path.join(outpath, os.path.basename(input_file))
    
    processing.run("saga:splitfeatureslayer", 
    {'SHAPES': input_files,
    'CUTS':'TEMPORARY_OUTPUT',
    'EXTENT':output_file,
    'NX':2,
    'NY':2,
    'METHOD':0}
    )

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, solveforum.

  • Arpit Aggarwal
  • 23 minutes ago
  • Geography
  • Replies: 0

Arpit Aggarwal Asks: Change background color of highlighted feature layer ArcGIS JavaScript
I have a feature layer and I am highlighting the feature of the feature layers on click. It is working fine.

Now what I want is, I want to change the background color / fill some color in that highlighted polygon feature.

Here is the code where I am highlighting the feature:

Code:

let highlight;
let highlightIds = [];

view.whenLayerView(districtLayer).then(function(layerView){
    view.on("click", (event) => {
        const params = {
            location: event.mapPoint
        };
        locator.locationToAddress(serviceUrl, params).then(function(response) { // Show the address found
            
            const district = response.attributes.Subregion;

            // remove all highlights first
            if(highlight) {
                highlight.remove();
            }

            // check if district is already highlighted
            let district_id = districtIds.indexOf(district) + 1;
            if(highlightIds.includes(district_id)){
                highlightIds.splice(highlightIds.indexOf(district_id), 1);
            }else{
                highlightIds.push(district_id);
            }

            // hightlight only the selected districts
            highlight = layerView.highlight(highlightIds);

            // code here to fill background color

        }, function(err) { // Show no address found
            console.log("No address found.", evt.mapPoint);
        });
    });
});

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, solveforum.

  • Shootforthemoon
  • 23 minutes ago
  • Biology
  • Replies: 0

Shootforthemoon Asks: Genetic Engineering Methods: An Overview of Key Approaches, Effectiveness, Costs, and Spectrum of Action
I am seeking a comprehensive list of the main or most noteworthy methods used in genetic engineering, in particular at the gene level. The focus should be on their effectiveness, costs (in terms of money and time), and spectrum of action (types of cells that can be successfully modified).

It is not necessary to explain the mechanisms in detail but instead accompany the list with key considerations in these areas. If available, kindly include references for data.

Thank you for your contribution!

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

  • Tarushi
  • 23 minutes ago
  • Chemistry
  • Replies: 0

Tarushi Asks: Is there a reaction involving alkene formation from diazomethane?
I need help regarding the following question…
enter image description here

I identified some of the compounds as follows:
enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

I’m confused about the formation of (G) from (H). Is there a way of preparing an alkene from another alkene by reacting it with diazomethane? Or have a recognised (G) incorrectly?

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

  • Jam War
  • 23 minutes ago
  • Physics
  • Replies: 0

Jam War Asks: Would it be possible in physics that ant-man shrinks by creating a warp bubble shell to shrink relatively to the universe but not actually change size
Would this be possible in physics and if not is there any other thing that could shrink antman from a relative point of view

(Would changing reference frames work?)

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

  • nodumbquestions
  • 23 minutes ago
  • Physics
  • Replies: 0

nodumbquestions Asks: In QM, does an algebra containing the Hamiltonian always evolve into itself?
Let $mathcal{A}$ be an algebra of operators on a Hilbert space $mathcal{H}$, and suppose it contains the Hamiltonian: $Hinmathcal{H}$. The Heisenberg evolution for any $hat{O}inmathcal{A}$ is $$tag{1} hat{O}(t)=e^{-itH}hat{O}(0)e^{itH}.$$

All three terms on the RHS are in $mathcal{A}$, and so $hat{O}(t)inmathcal{A}$ for all $t$. That is, time evolution maps $mathcal{A}$ into itself.


The above seems correct, but a particle moving on a line seems to provide a counterexample. Let $mathcal{H}=L^2(mathbb{R})$, with position and momentum operators $hat{x},hat{p}$. Take the Hamiltonian $H=hat{p}$. Finally, let $$tag{2}mathcal{A}={f(hat{x}):ftext{ is smooth },supp(f)subseteq (0,1)} oplus span(hat{p}).$$

To see that (2) is closed under the bracket, use $$tag{3}[f(hat{x}),hat{p}]=f'(hat{x})$$ and note that if $supp(f)subseteq (0,1)$ then $supp(f’)subseteq (0,1)$.

Now, since $hat{p}inmathcal{A}$, we expect $mathcal{A}$ to evolve into itself. But this is not true. We have begin{align} tag{4}f(hat{x})(t) &= f(hat{x}(t)) \ tag{5} &= f(e^{-ithat{p}} hat{x}(0) e^{ithat{p}}) \ tag{6}&= f(hat{x}(0)+tI ) end{align} where $I$ in the last line is the identity operator.

After unit time, any $f$ initially with support in $(0,1)$ evolves to have support outside $(0,1)$. Hence $mathcal{A}$ doesn’t evolve into itself.

Where was my mistake? Is there an issue with operators being unbounded? Note that in order to vanish outside $(0,1)$ but be nonzero inside, $f$ must be non-analytic — maybe this is somehow important?

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error ng areq
  • Error frame can bus
  • Error frame alliancedialog already encountered
  • Error found while importing rig in this animation file unity
  • Error found when loading home user profile

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии