【发布时间】:2020-05-15 15:10:28
【问题描述】:
在我的应用程序中,在更新该视图的模型后“刷新”该视图时遇到了很大的麻烦。主要是当 API 调用被解析并且其响应的数据应该在该视图上发布时。
这是我的组件management.component.tsts 文件(我已经删除了对这个问题不重要的代码):
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-service',
templateUrl: './service.component.html',
styleUrls: ['./service.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ServiceComponent implements OnInit {
serviceForm: FormGroup;
notificationStatus: boolean;
constructor(
private http: HttpClient
) { }
ngOnInit() {
this.buildServiceForm();
// Example endpoint response: { active: false }
this.getNotificationInfo().subscribe((data: object) => {
this.notificationStatus = data['active'];
})
}
submit()
{
this.notificationStatus = !this.notificationStatus;
}
buildServiceForm()
{
this.serviceForm = this.formBuilder.group({
message_de: ['', { validators: [Validators.required] }],
message_en: ['', { validators: [Validators.required] }]
});
}
getNotificationInfo() {
return this.http.get(this.apiPath + 'service/notifications');
}
}
这是 HTML 中负责显示该模型的部分(按钮标签):
<form [formGroup]="serviceForm" (ngSubmit)="submit()">
<mat-form-field class="service__form__textarea">
<textarea matInput formControlName="message_de"></textarea>
</mat-form-field>
<mat-form-field class="service__form__textarea">
<textarea matInput formControlName="message_en"></textarea>
</mat-form-field>
<button>
<span *ngIf="notificationStatus == false"> Service Off </span>
<span *ngIf="notificationStatus == true"> Service On </span>
</button>
</form>
每当单击按钮时,都会提交表单,并且应立即更新按钮的文本(使用 ngIf 进行更改)。但只有当我随机点击网站上的其他对象时才会发生这种情况。
我已经尝试过使用changeDetection: ChangeDetectionStrategy.OnPush,但没有运气。
这里的动画在实践中的样子 - 单击按钮后,其文本仅在单击 textarea 后才会更改,而不是在单击按钮后立即更改:
gif animation of the behavior
任何人都知道如何刷新我的视图或我的视图出现这种行为的原因是什么?
【问题讨论】:
标签: javascript angular