April 25, 2022

Angular - Can't bind to 'x' since it isn't a known property of 'y'

In Angular 11, I got this error:

error NG8002: Can't bind to 'x' since it isn't a known property of 'my-component'.
  1. If 'my-component' is an Angular component and it has 'x' input, then verify 
       that it is part of this module.
  2. If 'my-component' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the 
       '@NgModule.schemas' of this component to suppress this message.
  3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

Apparently it is telling the reasons behind it, but still it did not inform about which specific module is missing if you do not know it yourself.

While searching for my problem, I have found the following possible scenarios, which may cause this error.

  1. When you have defined a custom input field 'x' in your component, first thing to check is if the property 'x' is defined in your component with an proper Input() decorator.

    In Html:

    <my-component [someInputProperty]="someValue">
    	

    In .ts file:

    export class MyComponent {
    
      @Input()
      someInputProperty: string;
      ...
    }
    	
  2. Also check the spelling for property names (case-sensitive) to make sure its free from typo.

    In .ts file

    export class MyComponent {
    
      @Input()
      someInputProperty: string;
      ...
    }
    	

    In Html (wrong):

    <my-component [someinputproperty]="someValue">
    	

    Which should be (correct):

    <my-component [someInputProperty]="someValue">
    	
  3. If you have defined the component in a custom module, make sure that you have registered this component (or directive or pipe) class in NgModule's declarations array:

    @NgModule({
      ...
      declarations: [
    	...,
    	MyComponent
      ],
      ...
    })
    export class AModule { }
    	
  4. If you have defined the component in a custom module (AModule), and want to use it in another module (BModule). Make sure that you have registered this component (or directive or pipe) class in source (AModule) module's declarations array as well as exports array:

    @NgModule({
      ...
      declarations: [
    	...,
    	MyComponent
      ],
      ...
      exports: [
    	...,
    	MyComponent
      ],
    
    })
    export class AModule { }
    	
  5. For common Angular default attributes, we need to memorize the module needs to be imported. For example:

    • For ngFor attribute, we need to import CommonModule.
    • In a similar fashion, for ngModel we need to import FormsModule.

No comments:

Post a Comment