angularng-content

ng-content select not working "<element> is not a known element"


I am following this tutorial like so:

<div class="app-autocomplete">    
  <mat-form-field>
    <mat-form-field>
      <div class="app-autocomplete-input">
        <ng-content select="app-autocomplete-input"></ng-content>
      </div>
    </mat-form-field>
    <button mat-icon-button type="button" [disabled]="disabled">
      <mat-icon>clear</mat-icon>
    </button>
  </mat-form-field>

  <!-- ... --> 
</div>

But I am getting

Uncaught Error: Template parse errors: 'app-autocomplete-input' is not a known element:

  1. If 'app-autocomplete-input' is an Angular component, then verify that it is part of this module.
  2. If 'app-autocomplete-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (" [ERROR ->] ...

and I don't quite understand what the problem is here.

This is how I am trying to use app-autocomplete:

<app-autocomplete>          
  <app-autocomplete-input>
    <input placeholder="Yo"/>
  </app-autocomplete-input>          
</app-autocomplete>

Solution

  • Objective

    The actual objective of your is to leverage Content Projection to customize the component further while using.

    Issue

    The main issue is to use custom component app-autocomplete-input which is not provided anywhere.

    Fix

    Since you don't have custom component and never intended to have custom component. You use simple html tag like div span or you can use css class ex autocomplete-input.

    Modified code

    <div class="app-autocomplete">    
      <mat-form-field>
        <mat-form-field>
          <div class="app-autocomplete-input">
            <ng-content select=".app-autocomplete-input"></ng-content>
          </div>
        </mat-form-field>
        <button mat-icon-button type="button" [disabled]="disabled">
          <mat-icon>clear</mat-icon>
        </button>
      </mat-form-field>
    
      <!-- ... --> 
    </div>
    

    app-autocomplete.html

    <app-autocomplete>          
      <div class="app-autocomplete-input">
        <input placeholder="Yo"/>
      </div>          
    </app-autocomplete>