将不同的参数传递给角度组件的多个实例

  • 本文关键字:组件 实例 参数传递 angular
  • 更新时间 :
  • 英文 :


因此,我创建了一个简单的Angular组件custom-component,其中包含一个输入参数和一个点击按钮,我只是将参数值打印到控制台

输入参数声明

@Input() componentType: string;

组件实例创建-

<custom-component componentType="Type1"></custom-component>
<custom-component componentType="Type2"></custom-component>

内部的按钮点击事件处理程序

ngOnInit() {
console.log(this.componentType); // console prints Type1/Type2 here
}
onButtonClicked(event: any) {
console.log(this.componentType); // console prints Type1 always irrespective of which component is clicked
}

现在,我的问题是,无论我单击哪个组件按钮,它都会记录Type1。我尝试在ngOnInit((中进行调试,并确认在组件创建过程中传递了正确的值。

但是,一旦创建了组件,这些值就不会在下一次操作中保持(在这种情况下单击按钮(

您在如何使用Input:将数据传递给组件方面犯了一个错误

<custom-component [componentType]="Type1"></custom-component> // this way it will pass the updated data.
<custom-component [componentType]="Type2"></custom-component>

现在,另一个需要理解的部分是生命周期挂钩是如何工作的。因此,ngOnInit被调用一次并更新默认值,但当您根据任何事件(如click(更改值时,您需要实现ngOnChanges才能获得更新的值。

在组件实例中:

ngOnChanges() {
console.log(this.componentType); // console prints the updated values over time
}

查看此处了解更多详细信息。

最新更新