ANGULAR:单击组件上的事件



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

在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; 
}

正是出于这个原因,我避免使用Inputs,尽管完全有效,但我发现使用[Service]是一种更容易将大量数据传递给孩子的方法。TBH我发现更改指令上的绑定值对于跟踪和调试来说相当麻烦。

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

  1. 在您的应用程序中创建一个新服务,并在其中创建一个Subject或BehaviourSubject,并使用更新方法。

  2. 在你的父母身上(说(;点击";事件,创建匿名或键入的对象,并使用要发送给孩子的数据进行构建。

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

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

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

看起来您已经实现了接口OnChanges,但尚未声明该接口的方法ngOnChanges,这将导致错误。

无论如何,如果您想在更改发生时更新数据,则必须声明方法ngOnChanges,并相应地在其中实现代码。

示例:

ngOnChanges(changes: SimpleChanges) { 
//add your code here so that your data will change accordingly 
}

此外,你可以看看这个详细的解释。

就像前面其他人说的那样,你可以使用ngOnChanges((或在@Input方法上设置如下:

_name: string;
@Input() set name(value: string) {
this._name = value;
}
@Input() set amount(value: number) {
this.simulation.amount = value;
}
@Input() set rate(value: number) {
this.simulation.rate = value;
}
@Input() set duration(value: number) {
this.simulation.duration = value;
}
@Input() set delayed(value: number) {
this.simulation.delayed = value;
}

最新更新