2016-06-07 3 views
8

각도 1에서는 초과 된 템플릿 표현식에서 함수를 호출하는 것을 피했습니다. ng-repeat="item in vm.getFilteredItems()"은 결과가 getFilteredItems과 관련이 없기 때문에 함수가 다이제스트에 대해 반복적으로 불필요하게 재 계산되므로 일반적으로 규모에 따라 성능 문제가 발생합니다. 대신 객체에 바인딩하고 이벤트 (예 : ng-repeat="item in vm.filteredItems)를 기반으로 계산합니다.각도 2 : 컴포넌트 템플릿에서 함수에 바인딩

각도 2에서는 더티 확인 프로세스가 최적화되었지만 기능이 해당 속성에 종속적인지 여부에 관계없이 구성 요소 레벨의 속성이 변경되면 구성 요소 템플릿에서 호출되는 함수가 계속 호출됩니다. 부적절하게 사용하면 동일한 성능 문제가 발생할 수 있습니다.

// no function binding 
@Component({ 
    selector: 'nofunc', 
    template: ` 
    <input [(ngModel)]="searchTerm" (ngModelChange)="search($event)" placeholder="searchTerm" /> 
    <div *ngFor="let name of filteredNames">{{name}}</div> 
    ` 
}) 
export class NoFuncComponent implements OnInit { 
    @Input() names:string[]; 

    searchTerm: string; 

    ngOnInit() { 
    this.search(this.searchTerm); 
    } 

    search() { 
    if (!this.searchTerm) { 
     this.filteredNames = this.names; 
     return; 
    } 

    this.filteredNames = this.names.filter((name) => { 
     return name.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1; 
    }); 
    } 
} 

http://plnkr.co/edit/AAFknlJgso3D8F1w3QC1?p=preview

여전히 각도 2에 관심이가요 -

// function binding in template 
@Component({ 
    selector: 'func', 
    template: ` 
    <input [(ngModel)]="searchTerm" placeholder="searchTerm" /> 
    <div *ngFor="let name of filteredNames(searchTerm)">{{name}}</div> 
    ` 
}) 
export class FuncComponent { 
    @Input() names:string[]; 

    filteredNames(searchTerm) { 

    if (!searchTerm) return this.names; 

    let filteredNames = []; 

    return this.names.filter((name) => { 
     return name.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1; 
    }); 
    } 
} 

가 :

여기에 각도 2의 서로 다른 접근 방법의 단순화 된 예는? 어떤 접근 방식이 선호되며 그 이유는 무엇입니까? 감사!

답변

5

파이프를 만들 수 있습니다. 값이 변경되면 파이프 (pure)가 호출됩니다. 파이프 names의 변화를 인식 할 필요가있는 경우

@Pipe({ 
    name: 'search', 
// pure: 'false' 
}) 
class SearchPipe { 
    transform(names, searchTerm) { 
    if (!this.searchTerm) { 
     this.filteredNames = names; 
     return; 
    } 

    return names.filter((name) => { 
     return name.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1; 
    }); 
    } 
} 

@Component({ 
    selector: 'func', 
    pipes: [SearchPipe], 
    template: ` 
    <input [(ngModel)]="searchTerm" placeholder="searchTerm" /> 
    <div *ngFor="let name of names | search:searchTerm">{{name}}</div> 
    ` 
}) 
export class FuncComponent { 
    @Input() names:string[]; 
} 

다음 pure 사용 중지되어야한다. names이 대신 부재가 추가되거나 제거되는 다른 인스턴스로 대체되는 경우

pure 잘 작동 파이프 때만 namessearchTerm 또는 변경을 실행한다.

힌트 devMode (기본값) 변경 감지에

두 번 실행하고 파이프는만큼 예상대로 두 번 호출됩니다.