【问题标题】:Angular 9 ngOnChange: SimplesChanges.firstChange is always false but the value changedAngular 9 ngOnChange:SimplesChanges.firstChange 始终为 false,但值已更改
【发布时间】:2021-01-24 14:21:04
【问题描述】:

我有这个组件。我想在@Input 第一次更改时做点什么。问题是changes.firstChange 始终为假(在初始化时和更改后)。

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'test',
  templateUrl: './t.component.html',
  styleUrls: ['./t.component.css']
})
export class TComponent implements OnChanges {

  @Input()
  myValue: string;

  ngOnChanges(changes: SimpleChanges) {
    console.log('myValue:  ', changes.myValue.isFirstChange()); // always false
    console.log('myValue:  ', changes);
  }

}

为了使用它,我正在做:

  myValue = of('1').pipe(
    delay(2000),
    // startWith('2')
   )

我也试过了:

  myValue = '1'

<test [myValue]="myValue | async "></test> // 当使用of

正如您在图片中看到的那样,changes.firstChange 始终为 false,无论我稍后传递的是字符串还是新值。

这些是输出:

这是使用 rxjs 值时的输出:(value changed but never changed firstChange to true

【问题讨论】:

    标签: angular ngonchanges


    【解决方案1】:

    因为没有previousValue

    【讨论】:

    • 在某些时候会有第一个变化。它以 null 开头,然后有一个字符串值。即使启用了startWith,问题也是一样的。或者也只是传递一个字符串。
    猜你喜欢
    • 2015-02-12
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多