我有一个从外部获取一些参数的组件,然后根据这些参数构建其余的属性:
import { Component, Input } from '@angular/core';
import { NavController } from 'ionic-angular';
/*
Info card for displaying information in the homepage or another places
*/
@Component({
selector: 'info-card',
templateUrl: 'infocard.html'
})
export class InfoCard {
icon;
@Input() card = {
title: '',
description: '',
image: null,
type: 0
}
constructor(public navCtrl: NavController) {
// TODO: Complete type list
switch(this.card.type){
case 0: // Pubs/Entertainment
this.icon = "beer"; break;
case 1: // Restaurants
this.icon = "restaurant"; break;
case 2: // Friends
this.icon = "person"; break;
case 3: // Groups of people (private chats)
this.icon = "people"; break;
case 4: // Objective
this.icon = "checkbox-outline"; break;
default:
this.icon = "alert"; break;
}
// Image path
if(this.card.image){
this.card.image = '../../assets/infocards/'+this.card.image;
}
}
}
在构造函数中可以看到,根据卡的类型,它的图标如何设置。此外,如果图像与“null”不同,图像将仅被渲染,但我只想从其名称外部传递,因此我将构造函数放入文件夹的真实路径,并在结尾处连接图像名称。 / p>
我猜没什么奇怪的。然后,我尝试在我的代码中使用此组件:
<info-card *ngFor="let card of testCards" [card]="card">
</info-card>
卡片“正确”显示。我的意思是,模板渲染正常,但是图标和图像(取决于构造函数)都无法正常工作。类型0总是存在,所以我总是看到“啤酒”图标,图像被破坏(因为它没有指向正确的目录,而是指向一个名称)。
这导致了以下问题:构造函数何时运行?我认为在构造函数初始化之前会添加一个@Input值,但我想我错了。
如何正确构建从HTML传递数据的组件?
我只想在将属性“card”传递给组件后执行一些代码!
答案 0 :(得分:2)
您需要使用OnChanges:
import { Component, Input, OnChanges } from '@angular/core';
import { NavController } from 'ionic-angular';
/*
Info card for displaying information in the homepage or another places
*/
@Component({
selector: 'info-card',
templateUrl: 'infocard.html'
})
export class InfoCard implements OnChanges {
icon;
@Input() card = {
title: '',
description: '',
image: null,
type: 0
}
constructor(public navCtrl: NavController) {
}
ngOnChanges(changes) {
//changes will have your old card value and the new one
switch(this.card.type){
case 0: // Pubs/Entertainment
this.icon = "beer"; break;
case 1: // Restaurants
this.icon = "restaurant"; break;
case 2: // Friends
this.icon = "person"; break;
case 3: // Groups of people (private chats)
this.icon = "people"; break;
case 4: // Objective
this.icon = "checkbox-outline"; break;
default:
this.icon = "alert"; break;
}
// Image path
if(this.card.image){
this.card.image = '../../assets/infocards/'+this.card.image;
}
}
}