在Angular中,子组件的视图不更新可能是由于一些常见问题导致的,例如更改了输入属性但没有触发变化检测,或者使用了不正确的变更检测策略。
以下是一些解决方法:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
  selector: 'app-child',
  template: '{{ childValue }}'
})
export class ChildComponent implements OnChanges {
  @Input() parentValue: string;
  childValue: string;
  ngOnChanges(changes: SimpleChanges) {
    if (changes.parentValue) {
      this.childValue = changes.parentValue.currentValue;
    }
  }
}
import { Component } from '@angular/core';
@Component({
  selector: 'app-parent',
  template: `
    
    import { Component } from '@angular/core';
@Component({
  selector: 'app-parent',
  template: `
    
    import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
@Component({
  selector: 'app-child',
  template: '{{ childValue }}',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
  @Input() parentValue: string;
  childValue: string;
}
import { Component, Input } from '@angular/core';
@Component({
  selector: 'app-child',
  template: '{{ childValue }}'
})
export class ChildComponent {
  @Input() parentValue: string;
  childValue: string;
}
通过检查这些常见问题,并应用适当的解决方法,你应该能够解决子组件视图不更新的问题。