将数据从第一个组件发送到第二个组件Angular

时间:2017-10-18 20:52:04

标签: angular

这是我的第一部分

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

我可以从第一个组件获取输入框的Sum值,但不能将它发送到第二个组件。我试图使用输出,但它没有用。我哪里错了? 这是我的stackblitz链接代码

https://stackblitz.com/edit/get-value-from-other-component?file=app%2Ftotal.component.ts

1 个答案:

答案 0 :(得分:1)

代码已更新 https://stackblitz.com/edit/get-value-from-other-component-tsbko6?file=app%2Famount.component.ts

您错误地使用了事件发射器。其次,在您的应用程序组件中,您没有订阅该事件,然后您需要将该值作为第二个组件的输入传递。