在这种情况下,我正在向视图中显示学生列表(数组)ngFor:
<li *ngFor="#student of students">{{student.name}}</li>
Run Code Online (Sandbox Code Playgroud)
每当我将其他学生添加到列表中时,它都会更新.
然而,当我给它一个pipe到filter由学生的名字,
<li *ngFor="#student of students | sortByName:queryElem.value ">{{student.name}}</li>
Run Code Online (Sandbox Code Playgroud)
在我在过滤学生姓名字段中输入内容之前,它不会更新列表.
这是plnkr的链接.
Hello_world.html
<h1>Students:</h1>
<label for="newStudentName"></label>
<input type="text" name="newStudentName" placeholder="newStudentName" #newStudentElem>
<button (click)="addNewStudent(newStudentElem.value)">Add New Student</button>
<br>
<input type="text" placeholder="Search" #queryElem (keyup)="0">
<ul>
<li *ngFor="#student of students | sortByName:queryElem.value ">{{student.name}}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
sort_by_name_pipe.ts
import {Pipe} from 'angular2/core';
@Pipe({
name: 'sortByName'
})
export class SortByNamePipe {
transform(value, [queryString]) {
// console.log(value, queryString);
return value.filter((student) => new RegExp(queryString).test(student.name))
// return value;
} …Run Code Online (Sandbox Code Playgroud) 我是Angular2和TypeScript的新手.我正在关注教程,但我一直在处理这个错误.这是编译器或其他什么引起的错误吗?

这是我的代码
@Component({
template: `<h1>Hello from A</h1>
<ul>
<li *ngFor="#letter of letters; #i = index">
<button (click)="appendW(i)">{{letter | uppercase}}</button>
</li>
</ul>
<button (click)="doSomething()">Click</button>`,
pipes: [UpperCasePipe],
directives: [NgFor]
})
export class AComponent {
letters = ['a','b','c','d'];
contructor(){
}
appendW(index) {
// console.log(letter);
setTimeout(()=>{
this.letters[index] += "W";
}, 1000)
}
...
}
Run Code Online (Sandbox Code Playgroud)
在setTimeout之后,对内容和视图进行两次角度检查.有人可以解释一下吗?为什么角度需要检查TWICE?
我有一个简单的管道,可以过滤一系列学生.这是代码(Plnkr)
import {Pipe} from 'angular2/core';
@Pipe({
name: 'sortByName',
pure: false
})
export class SortByNamePipe {
temp = [];
// i = 0;
transform (value, [queryString]) {
// console.log(this.i++);
// console.log(value, queryString);
// This does not work
this.temp = value.filter((student)=>(student)=>student.name.includes(queryString)))
return value.map(function(val){ return val.name.toUpperCase()});
// This works
// this.temp.length = 0;
// this.temp.push(...value.filter((student)=>student.name.includes(queryString)))
// return this.temp;
}
}
Run Code Online (Sandbox Code Playgroud)
正如您在Plnkr中看到的,Angular使用第一种方法抛出错误.
EXCEPTION: Expression 'students | sortByName:queryElem.value in HelloWorld@7:6' has changed after it was checked. Previous value: 'SON,DAVID'. Current value: 'SON,DAVID' in …Run Code Online (Sandbox Code Playgroud)