我有一个组件,它接收image个对象的数组作为Input个数据.

export class ImageGalleryComponent {
  @Input() images: Image[];
  selectedImage: Image;
}

我想在组件加载时,将selectedImage值设置为images数组的第一个对象.我试着在OnInit生命周期钩子中这样做:

export class ImageGalleryComponent implements OnInit {
  @Input() images: Image[];
  selectedImage: Image;
  ngOnInit() {
    this.selectedImage = this.images[0];
  }
}

这给了我一个错误Cannot read property '0' of undefined,这意味着images值没有在这个阶段设置.我也try 过OnChanges钩子,但我被卡住了,因为我无法获得有关如何观察数组变化的信息.我怎样才能达到预期的结果?

父组件如下所示:

@Component({
  selector: 'profile-detail',
  templateUrl: '...',
  styleUrls: [...],
  directives: [ImageGalleryComponent]
})

export class ProfileDetailComponent implements OnInit {
  profile: Profile;
  errorMessage: string;
  images: Image[];
  constructor(private profileService: ProfileService, private   routeParams: RouteParams){}

  ngOnInit() {
    this.getProfile();
  }

  getProfile() {
    let profileId = this.routeParams.get('id');
    this.profileService.getProfile(profileId).subscribe(
    profile => {
     this.profile = profile;
     this.images = profile.images;
     for (var album of profile.albums) {
       this.images = this.images.concat(album.images);
     }
    }, error => this.errorMessage = <any>error
   );
 }
}

父组件的模板包含以下内容:

...
<image-gallery [images]="images"></image-gallery>
...

推荐答案

在调用ngOnInit()之前填充输入属性.但是,这假设在创建子组件时,为输入属性提供信息的父属性已经填充.

In your scenario, this is not the case – the images data is being populated asynchronously from a service (hence an http request). Therefore, the input property will not be populated when ngOnInit() is called.

为了解决您的问题,当数据从服务器返回时,为父属性分配一个新array.在子元素身上实现ngOnChanges().当Angular 变化检测将新数组值向下传播到子数组时,将调用ngOnChanges().

Typescript相关问答推荐

我可以让Typescript根据已区分的联合键缩小对象值类型吗?

类型脚本:类型是通用的,只能索引以供阅读.(2862)"

如何根据数据类型动态注入组件?

类型是工作.但它失go 了正确变体的亮点..为什么?或者如何增强?

Angular 17 -如何在for循环内创建一些加载?

当使用`type B = A`时,B的类型显示为A.为什么当`type B = A时显示为`any `|用A代替?

将对象属性转换为InstanceType或原样的强类型方法

隐式键入脚本键映射使用

为什么T[数字]不也返回UNDEFINED?

如果字符串文字类型是泛型类型,则用反引号将该类型括起来会中断

ApexCharts条形图未显示最小值.负值

类型脚本可以推断哪个类型作为参数传递到联合类型中吗?

有没有办法取消分发元组的联合?

为什么S struct 类型化(即鸭子类型化)需要非严格类型联合?

接受字符串或数字的排序函数

如何正确地将元组表格输入到对象数组实用函数(如ZIP)中,避免在TypeScrip 5.2.2中合并所有值

使用强类型元组实现[Symbol.iterator]的类型脚本?

有没有更干净的方法来更新**key of T**的值?

为什么`map()`返回类型不能维护与输入相同数量的值?

组件使用forwardRef类型脚本时传递props