
在本教程中,学习如何修复Angular内置指令中的问题
- 无法绑定 "ngIf",因为它不是 "div "的已知属性。
- 异常。不能绑定到'ngFor',因为它不是已知的本地属性。
让我们创建一个Angular组件来测试这个。
A:\work\angular-convert-examples>ng generate component ngif-test
CREATE src/app/ngif-test/ngif-test.component.html (24 bytes)
CREATE src/app/ngif-test/ngif-test.component.spec.ts (641 bytes)
CREATE src/app/ngif-test/ngif-test.component.ts (287 bytes)
CREATE src/app/ngif-test/ngif-test.component.scss (0 bytes)
UPDATE src/app/app.module.ts (677 bytes)
ngif-test.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-text',
templateUrl: './ngif-test.component.html',
styleUrls: ['./ngif-test.component.scss']
})
export class TextComponent implements OnInit {
constructor() { }
isActive = true;
ngOnInit(): void {
}
}
ngif-test.component.html
text works!
Active=true
原因可能是由于语法不正确或缺少依赖模块。
Angular无法绑定到'ngIf'的解决方案,因为它不是'div'的已知属性
有多种方法可以解决这个问题。
不正确的ngIf语法一种方法,这是由于div的大写字母 "I "拼错了造成的错误。
它应该从
正确的方法是使用
Active=true
缺少模块
为了解决这个问题,在app.module.ts中导入CommonModule 或BroswerModule 或两者。
CommonModule:它提供了一个内置的模板,如ngIf ngFor指令在angular应用程序中。BrowserModule :它包含指令和服务,以在浏览器上启动和运行代码,同时它也导入了CommonModule
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/common';
@NgModule({
imports: [
CommonModule,
BrowserModule
],
declarations: [],
providers: [],
exports: [],
})
export class app.module.ts { }
懒于加载父子模块
这也是由于父模块和子模块的懒惰加载模块中缺少模块造成的。为了解决这个问题,在父模块导入BrowserModule ,在子模块导入CommonModule 。根模块总是导入browserModule,而功能模块或子模块导入commonmodule。
导入模块后,模块文件如下所示。
parent.module.ts
import { BrowserModule } from '@angular/common';
@NgModule({
imports: [
BrowserModule
],
declarations: [],
providers: [],
exports: [],
})
export class ParentModule { }
child.module.ts
import { CommonModule } from '@angular/common';
@NgModule({
imports: [
CommonModule,
],
declarations: [],
providers: [],
exports: [],
})
export class ChildModule { }
让我们看看如何在Angular单元测试中解决这个错误。
Angular测试-jasmine karma测试案例修复
有时,当你写一个单元测试的Angular组件。你会遇到这个错误。
请确保BrowserModule被导入到模块规格文件中。
还有,如果你使用父子模块,父模块应该导入BrowserModule,子模块应该导入commonmodule。
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { BrowserModule } from '@angular/platform-browser';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule,
BrowserModule
],
declarations: [
AppComponent
],
}).compileComponents();
});
});