Can't bind to 'ngIf' since it isn't a known property of 'ng-container'

Viewed 3727

The same thing is asked like 1000 times but I have CommonModule Injected.

I have a lazy-loaded module and used on multiple routes like inside the main layout and outside of it

It works perfectly but when I run tests cases in it, they keep throwing Can't bind to 'ngIf' since it isn't a known property of 'ng-container' even though I have injected common module and ViewChild is also returning undefined if it's inside ngIf or even if it's not the ViewChild just returns the start end tag of the component called.

HTML of the in question module ( Test Module )

<ng-container *ngIf="step === 'search'">
  <app-search #search></app-search>
<ng-container>
<app-unsaved #unsaved></app-unsaved>

Component

@ViewChild('unsaved') unsaved: UnsavedComponent;
@ViewChild('search') search: SearchComponent;

Routing

In main layout

{
    path: 'test',
    canActivate: [ValidatedGuard],
    loadChildren: () => import('@app/test.module').then(mod => mod.TestModule)
},

In lazy loaded routing

{ path: '', component: TestComponent, canDeactivate: [CanDeactivateGuard] }

Everything looks and it works fine but when I run the tests cases,

WARN LOG: 'Can't bind to 'ngIf' since it isn't a known property of 'ng-container'.'

and

ElementRef{nativeElement: <app-unsaved></app-unsaved>}



@NgModule({
    declarations: [
        TestComponent
    ],
    imports: [
        TestRouting,
        CommonModule,
        SearchModule,
        QuotesModule,
        ConfirmModule,
        UnsavedModule
    ]
})

export class TestModule { }


const routes: Routes = [
    { path: '', component: TestComponent, canDeactivate: [CanDeactivateGuard] }
];

export const TestRouting = RouterModule.forChild(routes);
1 Answers

To conditionally show something with ng-container use *ngTemplateOutlet attribute.

The value you give it should be template reference of an element and do a ternary operator if you want to show it or not.

<ng-container *ngTemplateOutlet="step === 'search' ? appSearch : null">
<ng-container>

<ng-template #appSearch><app-search #search></app-search></ng-template>
Related