Angular中的条件chagngeDetectionStrategy?

时间:2018-08-05 08:04:46

标签: javascript angular

我在Angular中有一个卡片组件:

enter image description here

请注意星级也是一个组成部分。

但是,在这种特殊情况下,用户不能点击星号,因为这是只读信息。

其他组件中使用了相同的星级评分组件来实际设置费率)

这是“星星”组件的精髓:

@Component({
    moduleId   : module.id,
    selector   : 'app-stars-rating',
    templateUrl: './stars.component.html',
    styleUrls  : ['./stars.component.scss'],
    providers  : [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})

问题:

正在查看:

 <Card col="1" row="2">
        <app-stars-rating [disabled]="true" [isSmall]="true">
        </app-stars-rating>
 </Card >

是否可以有条件地changeDetection: ChangeDetectionStrategy.OnPush组件上设置app-stars-rating

换句话说:

<Card col="1" row="2">
        <app-stars-rating [isOnPush]="someVal" ...>
        </app-stars-rating>
 </Card >

1 个答案:

答案 0 :(得分:1)

有条件设置 OnPush更改检测的最接近的方法是在禁用编辑时从更改检测树 detach视图。

public class StarsComponent {
  @Input() public disabled: boolean;

  constructor(private cdRef: ChangeDetectorRef) {}

  public ngOnInit(): void {
     // Init
     if (this.disabled) {
       this.cdRef.detach();
     }
  }

  public refreshManual(): void {
     this.cdRef.detectChanges();     
  }
}

在您明确调用 detectChanges()方法之前,这将防止在组件上运行更改检测。如果组件随后需要再次启用更改检测,则可以通过调用reattach()方法来添加它。