首页 > 解决方案 > 反应式表单控件触发更改检测

问题描述

每当输入值更改时,都会触发反应FormControl元素。ChangeDetection我添加了OnPush策略,但它仍然运行ChangeDetection

@Component({
  selector: 'app-server-input',
  templateUrl: './server-input.component.html',
  styleUrls: ['./server-input.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

FormControl指令是触发的指令ChangeDetectionChangeDetection输入更改时如何停止运行?

serverName: FormControl = new FormControl();

这是我在 StackBlitz 上的代码。

注意:这里要注意的一件事是,如果您单击按钮,则会调用 ngDocheck,因此我使用事件管理器来停止更改检测。

标签: angularangular2-changedetectionangular-changedetection

解决方案


ngDoCheck总是运行。不管你使用什么策略。请参阅https://indepth.dev/posts/1131/if-you-think-ngdocheck-means-your-component-is-being-checked-read-this-article以及我们为什么需要`ngDoCheck`

我看不出您有任何理由想知道何时、如何运行更改检测。如果您想对更改做一些事情,只需在您的输入上使用 setter:

_name: string;
get name(): string{
    return this._name;
}
@Input() set name(value: string) {
    this._name = value;
    this.doUpdateSomething();
}

推荐阅读