首页 > 解决方案 > 角度:单击组件上的事件

问题描述

我有两个组件,它们具有相同的孩子但输入不同。

在 ogOnInit 的子项中,我启动了模型中的输入。当我第一次单击其中一个组件时,孩子的 html 被更新,但是当我再次单击时,我仍然将最后一个组件的输入保存在 dom 中。

这是正常的,因为组件在 dom 中只加载一次,而 ngOnInit 只执行一次。

所以,我需要找到一个解决方案,每次点击都更新孩子的数据。

这是我的代码:

第一个组件:

import { Component } from '@angular/core';

@Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page {}

  <app-explore-container amount="1000000" delayed="0" rate="5" duration="180" name="Crédit Immobilier"></app-explore-container>

第二部分:

 @Component({
 selector: 'app-tab2',
 templateUrl: 'tab2.page.html',
 styleUrls: ['tab2.page.scss']
 })
 export class Tab2Page {}

  <app-explore-container amount="200000" delayed="0" rate="6.0" duration="60" name="Crédit Consommation"></app-explore-container>

子组件:

@Component({
  selector: 'app-explore-container',
  templateUrl: './explore-container.component.html',
  styleUrls: ['./explore-container.component.scss']
})
export class ExploreContainerComponent implements OnInit, OnChanges {
  @Input() name: string;
  @Input() amount: number;
  @Input() rate: number;
  @Input() duration: number;
  @Input() delayed: number;

  constructor(public simulation: Simulateur) { }

ngOnInit() {
  this.simulation.amount = this.amount;
  this.simulation.rate = this.rate;
  this.simulation.duration = this.duration;
  this.simulation.delayed = this.delayed; 
}

标签: angularevent-handling

解决方案


出于这个原因,我避免使用 Inputs,虽然完全有效,但我发现使用 [Service] 是一种更简单的方法,可以将大量数据传递给孩子。TBH 我发现更改指令上的绑定值而不是跟踪和调试的笨拙。

作为替代方案,我可以建议您使用服务的数据传输来代替...

  1. 在您的应用程序中创建一个新服务,并在其中创建一个主题或行为主题,并使用更新它的方法。

  2. 在您的父母(比如)上的“点击”事件上,创建一个匿名或类型化的对象,并使用要发送给您孩子的数据进行构建。

  3. 注入您的服务并将您的点击数据发送给主题。

  4. 在您的子组件上,还注入您的服务并订阅主题以获取最新的点击数据。

您的孩子将始终获得最新的参数。


推荐阅读