Angular 2 - 禁用变化检测

时间:2018-03-26 04:49:42

标签: angular

您好我有聊天消息的组件。我有变化检测的问题。当我键入时,ngFor指令仍然重绘所有消息。我想在显示此组件时绘制消息,然后在添加新消息之后。这是我的代码:

chat.component.ts:

@Component({
    selector: 'my-chat',
    templateUrl: './chat.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChatComponent implements OnInit {
    text: string;
    @Input() messages: ChatMessage[];
    @Output() onChanged: EventEmitter<string> = new EventEmitter<string>();
    constructor(private app: App, private cd: ChangeDetectorRef) {}

    ngOnInit() {
        this.messages = !this.messages ? [] : this.messages;        
    }

    onChangeHandler(value: string) {
        this.onChanged.emit(value);
    }

    trackByFn(index, item){
        console.log(index, item); //still calls when typing
        return item.Id;
    }
}

export interface ChatMessage {
    Text: string;
}

chat.component.html:

<form action="#" method="post" *ngIf="!readonly" [style.margin-bottom]="'10px'">
    <div class="img-push" [ngClass]="{'input-group': enableSaveButton}">
        <textarea class="form-control input-sm" rows="2" style="resize:none" [(ngModel)]="text" [ngModelOptions]="{standalone: true}"
         (ngModelChange)="onChangeHandler($event)"></textarea>
    </div>
</form>
<div class="box-body box-comments pre-scrollable">
    <ng-container *ngIf="messages.length != 0">
        <div class="box-comment" *ngFor="let message of messages; let i=index;trackBy:trackByFn">
            <div class="comment-text">
                <pre>{{message.Text}}</pre>
            </div>
        </div>
    </ng-container>
</div>

1 个答案:

答案 0 :(得分:1)

我完全尝试了您的代码段,发现*ngFor 规则下的元素未被重新呈现。更改文本时仍会调用trackByFn函数,但仅作为ngDoCheck调用NgForOf中的一部分调用,这是一个在使用{{1时自动创建的指令}}

您可以在DOM检查器中的devtools中验证Chrome。如果要重新渲染元素,您会看到与此处enter image description here大致相同(取自this article