我创建了一个无法正常工作的管道。 代码似乎很简单明了,但我还没弄清楚出了什么问题。
有什么想法吗?
我的app.module
:
import { HeroModule } from "./hero/hero.module";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, HeroModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
我的hero.module
:
import { HeroComponent } from './hero.component';
import { FlyersPipe } from '../pipes/flyers.pipe';
@NgModule({
imports: [
CommonModule
],
declarations: [HeroComponent, FlyersPipe],
exports: [HeroComponent, FlyersPipe]
})
export class HeroModule { }
我的flyers.pipe.ts
:
import { Pipe, PipeTransform } from '@angular/core';
import { Hero } from '../model/hero';
@Pipe({
name: 'appflyers'
})
export class FlyersPipe implements PipeTransform {
transform(heroes: Array<Hero>, args?: any): any {
console.info(heroes);
return heroes.filter(hero => hero.canFly);
}
}
最后,我的hero.component.html
:
<div *ngFor="let hero of heroes | appflyers">
{{hero | json}}
</div>
修改
我正在使用以下代码将英雄添加到heroes
HeroComponent属性中:
<input type="text" #box
(keyup.enter)="addHero(box.value); box.value=''"
placeholder="hero name">
<input type="checkbox" [checked]="canFly" (change)="canFly = !canFly"/>
hero.component.ts
:
import { Component, OnInit } from '@angular/core';
import { Hero } from '../model/hero';
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
private heroes: Array<Hero> = new Array<Hero>();
private canFly: boolean = true;
constructor() { }
ngOnInit() {
}
private addHero(name: string) {
this.heroes.push(new Hero(name, null, this.canFly));
}
private reset() { this.heroes = this.heroes.slice(); }
}
答案 0 :(得分:1)
我认为您的方案正是pipe documentation描述的
请注意实例/下载示例中的奇怪行为:当您添加飞行英雄时,其中没有一个显示在&#34;飞行的英雄下。&#34;
管道默认是纯的,这意味着如果输入没有改变,它们就不会在变更检测中执行。
只有在检测到输入值的纯变化时,Angular才会执行纯管道。纯变化是对原始输入值(String,Number,Boolean,Symbol)的更改或更改的对象引用(Date,Array,Function,Object)。
Angular忽略(复合)对象内的更改。如果更改输入月份,添加到输入数组或更新输入对象属性,它将不会调用纯管道
为了使其工作,您可以将管道变成不纯的管道,这意味着它将在每次变化检测循环期间执行。如果管道执行的操作很快,那就没问题。
@Pipe({
name: 'appflyers',
pure: false
})
另一个解决方案是保持管道纯净并在添加新英雄时更改对数组的引用(例如使用扩展运算符)
private addHero(name: string)
{
this.heroes = [...this.heroes, new Hero(name, null, this.canFly)];
}