如何在第二次触发 *ngIf 时删除旧的 DOM 内容
How to remove old DOM content when *ngIf is triggered for the second time
我有一个 Angular 2 组件,如下所示:
<div *ngIf="Data"> This is my data: {{Data}} </div>
哪个输出(为方便起见,假设数据只是一个字符串 "Data")
This is my data: Data
在我的控制器的 OnInit 函数中,我订阅了一个不时更新此数据对象的可观察对象。
我的控制器的 onInit 函数如下所示:
ngOnInit() {
this.dataEvent.subscribe(Data=> this.Data = Data);
}
更新发生时,组件意识到发生了变化,并显示新数据。但不清除旧数据,所以我最终得到:
This is my data: DataThis is my data: NewData
我试图在呈现新数据之前清除 DOM 元素,以便我的组件只显示
This is my data: NewData
observable触发更新后。我对 *ngFor 也有类似的问题,但我认为两者都有一个共同的解决方案。
好吧,我是愚蠢的,没有注意我应该注意的控制台警告。我使用的是 运行 typescript 2.6.0,但我正在处理的 angular 项目需要旧版本。警告是:
@angular/compiler-cli@4.3.6 requires typescript@'>=2.1.0 <2.4.0' but 2.6.0 was found instead.
Using this version can result in undefined behaviour and difficult to debug problems.
Please run the following command to install a compatible version of TypeScript.
npm install typescript@'>=2.1.0 <2.4.0'
To disable this warning run "ng set --global warnings.typescriptMismatch=false".
而且只是 运行:
npm install typescript@2.3.4
立即解决了我的问题。希望这可以帮助其他人,当警告字面意思是它可能导致难以调试问题时,不要浪费他们生命中的几个小时来调试问题 >.<
我有一个 Angular 2 组件,如下所示:
<div *ngIf="Data"> This is my data: {{Data}} </div>
哪个输出(为方便起见,假设数据只是一个字符串 "Data")
This is my data: Data
在我的控制器的 OnInit 函数中,我订阅了一个不时更新此数据对象的可观察对象。 我的控制器的 onInit 函数如下所示:
ngOnInit() {
this.dataEvent.subscribe(Data=> this.Data = Data);
}
更新发生时,组件意识到发生了变化,并显示新数据。但不清除旧数据,所以我最终得到:
This is my data: DataThis is my data: NewData
我试图在呈现新数据之前清除 DOM 元素,以便我的组件只显示
This is my data: NewData
observable触发更新后。我对 *ngFor 也有类似的问题,但我认为两者都有一个共同的解决方案。
好吧,我是愚蠢的,没有注意我应该注意的控制台警告。我使用的是 运行 typescript 2.6.0,但我正在处理的 angular 项目需要旧版本。警告是:
@angular/compiler-cli@4.3.6 requires typescript@'>=2.1.0 <2.4.0' but 2.6.0 was found instead.
Using this version can result in undefined behaviour and difficult to debug problems.
Please run the following command to install a compatible version of TypeScript.
npm install typescript@'>=2.1.0 <2.4.0'
To disable this warning run "ng set --global warnings.typescriptMismatch=false".
而且只是 运行:
npm install typescript@2.3.4
立即解决了我的问题。希望这可以帮助其他人,当警告字面意思是它可能导致难以调试问题时,不要浪费他们生命中的几个小时来调试问题 >.<