无法绑定到“ ngIf”,因为它不是“ ng-container”的已知属性

时间:2020-07-07 10:10:38

标签: angular lazy-loading

同一件事被问了1000次,但是我已经注入了CommonModule。

我有一个延迟加载的模块,并用于多种布局,例如主布局内部和外部

它可以正常工作,但是当我在其中运行测试用例时,即使我注入了通用模块,并且它们仍会抛出Can't bind to 'ngIf' since it isn't a known property of 'ng-container',如果它在ngIf内甚至不是ViewChild时,ViewChild也返回undefined。

有问题的模块(测试模块)的HTML

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

组件

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

路由

在主布局中

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

在延迟加载路由中

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

一切看起来都很正常,但是当我运行测试用例时,

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

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 个答案:

答案 0 :(得分:0)

要使用ng-container属性有条件地显示某些内容,请使用*ngTemplateOutlet属性。

您赋予它的值应该是元素的模板引用,并且如果不想显示它,请执行三元运算符。

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

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