ChangeDectioncss
檢測程序內部狀態,而後反映到UI上。html
引發狀態變化:Events,XHR,Timersapp
ApplicationRef監聽NgZone的onTurnDone,而後執行檢測。ide
OnPush狀態徹底由外部決定,內部不會去改變狀態。 測試
例子:this
把聰明組件project-list變成OnPush檢查策略,spa
在須要檢測時候使用cd.markForCheck).code
@Component({ selector: "app-project-list", templateUrl: "./project-list.component.html", styleUrls: ["./project-list.component.scss"], animations:[ slideToRight,listAnimation ], changeDetection: ChangeDetectionStrategy.OnPush })
手動告訴Angualr你來檢查我component
在事件發生的時候主動告訴Angular來檢查這條路線。router
import { Component, OnInit , HostBinding, ChangeDetectionStrategy, ChangeDetectorRef } from "@angular/core"; import { MatDialog } from "@angular/material"; import { NewProjectComponent } from "../new-project/new-project.component"; import { InviteComponent } from '../invite/invite.component'; import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component'; import {slideToRight} from '../../animate/router.animate' import { listAnimation } from '../../animate/list.animate'; import { projection } from '@angular/core/src/render3'; @Component({ selector: "app-project-list", templateUrl: "./project-list.component.html", styleUrls: ["./project-list.component.scss"], animations:[ slideToRight,listAnimation ], changeDetection: ChangeDetectionStrategy.OnPush }) export class ProjectListComponent implements OnInit { @HostBinding('@routeAnim') state; projects = [ { id:1, name: "企業協做平臺", desc: "這是一個企業內部項目", coverImg: "assets/images/covers/0.jpg" }, { id:2, name: "自動化測試項目", desc: "這是一個企業內部項目", coverImg: "assets/images/covers/2.jpg" } ]; constructor(private dialog: MatDialog, private cd:ChangeDetectorRef) { } ngOnInit() { } openNewProjectDialog() { // this.dialog.open(NewProjectComponent,{data:'this is a dialog'}); const dialogRef = this.dialog.open(NewProjectComponent, { data: { title: '新建項目' } }); dialogRef.afterClosed().subscribe((result) => { console.log(result); this.projects = [...this.projects, {id:3,name:'一個新項目',desc:'這是一個新項目',coverImg:"assets/images/covers/3.jpg"}, {id:4,name:'又一個新項目',desc:'這是又一個新項目',coverImg:"assets/images/covers/4.jpg"}] }); this.cd.markForCheck(); } lauchInviteDialog() { const dialogRef = this.dialog.open(InviteComponent); } lauchUpdateDialog() { const dialogRef = this.dialog.open(NewProjectComponent, { data: { title: '編輯項目' } }); } lauchConfimDialog(project) { const dialogRef = this.dialog.open(ConfirmDialogComponent, { data: { title: '刪除項目', content: '您確認刪除該項目嗎?' } }); dialogRef.afterClosed().subscribe(result=>{ console.log(result); this.projects=this.projects.filter(p=>p.id!=project.id); this.cd.markForCheck(); }); } }
把笨組件標識爲OnPush
直接加changeDetection:ChangeDetectionStrategy.OnPush
@Component({ selector: 'app-new-project', templateUrl: './new-project.component.html', styleUrls: ['./new-project.component.scss'], changeDetection:ChangeDetectionStrategy.OnPush })