Angular 将数据从第一个组件发送到第二个组件
这是我的第一部分Angular 将数据从第一个组件发送到第二个组件,angular,Angular,这是我的第一部分 @Component({ selector: 'app-amount', template: ` <h3>Amount component</h3> <form #f = "ngForm" (ngSubmit)="onSubmit(f)"> <input type="number" name="number" ngModel id="numbe
@Component({
selector: 'app-amount',
template: `
<h3>Amount component</h3>
<form #f = "ngForm" (ngSubmit)="onSubmit(f)">
<input type="number" name="number" ngModel id="number">
<button type='submit'>Add</button>
</form>
<div *ngFor="let item of numberArray" >{{item}}</div>
<div>Total: {{total}}</div>
`
})
export class Amount {
@Output () total = new EventEmitter<number>();
@ViewChild('') submitForm: NgForm;
numberArray = [];
constructor(){
}
onSubmit(form: NgForm){
const total = 0;
this.numberArray.push(form.value.number);
this.total = this.numberArray.reduce((prev: number, next: number)=>{
//this.total.emit(prev + next);
return prev + next;
})
}
}
@Component({
selector: 'app-total',
template: `
<h3>Total component</h3>
<span>I want the Total value appear here. What is the best way to implment/get?</span>
<p></p>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class Total {
totalValue;
total(number: number){
this.totalValue = number;
}
}
@组件({
选择器:'应用程序金额',
模板:`
金额构成
添加
{{item}}
总计:{{Total}
`
})
出口类金额{
@输出()总计=新的EventEmitter();
@ViewChild(“”)提交格式:NgForm;
numberArray=[];
构造函数(){
}
onSubmit(表格:NgForm){
const-total=0;
this.numberArray.push(form.value.number);
this.total=this.numberArray.reduce((上一个:数字,下一个:数字)=>{
//this.total.emit(上一个+下一个);
返回上一个+下一个;
})
}
}
这是第二部分
@Component({
selector: 'app-amount',
template: `
<h3>Amount component</h3>
<form #f = "ngForm" (ngSubmit)="onSubmit(f)">
<input type="number" name="number" ngModel id="number">
<button type='submit'>Add</button>
</form>
<div *ngFor="let item of numberArray" >{{item}}</div>
<div>Total: {{total}}</div>
`
})
export class Amount {
@Output () total = new EventEmitter<number>();
@ViewChild('') submitForm: NgForm;
numberArray = [];
constructor(){
}
onSubmit(form: NgForm){
const total = 0;
this.numberArray.push(form.value.number);
this.total = this.numberArray.reduce((prev: number, next: number)=>{
//this.total.emit(prev + next);
return prev + next;
})
}
}
@Component({
selector: 'app-total',
template: `
<h3>Total component</h3>
<span>I want the Total value appear here. What is the best way to implment/get?</span>
<p></p>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class Total {
totalValue;
total(number: number){
this.totalValue = number;
}
}
@组件({
选择器:“应用程序总数”,
模板:`
总成分
我希望总价值出现在这里。实施/获取的最佳方式是什么?
`,
样式:[`h1{font-family:Lato;}`]
})
出口类总计{
总价值;
总数(个数:个数){
this.totalValue=数字;
}
}
我可以从第一个组件获取输入框的和值,但无法将其发送到第二个组件。我试图使用输出,但没有成功。我错在哪里? 这是我的stackblitz链接代码 代码已更新
您错误地使用了事件发射器。其次,在应用程序组件中,您没有订阅事件,然后需要将该值作为输入传递给第二个组件。可能重复我尝试使用输出,但它不起作用。我不知道我错在哪里。您需要一个服务来在组件之间共享数据。