简体   繁体   中英

How to change a variable value by 10 which is defined in parent component and accessed in child component using button?

I am trying to make some application and i don't know how to change a variable value that is defined in parent component and acessed in child component. Below is the code for child component: This is child component.html code:

    <p>Child Component Works!</p>
   <h2>{{name.name1}}</h2>
   <h4>{{name.Money1}}</h4>
    <h2>{{name.name2}}</h2>
   <h4>{{name.Money2}}</h4>

child component.ts code:

    import { Component, EventEmitter,  OnInit, Input } from "@angular/core";

   @Component({
  selector: 'app-child-component',
  templateUrl: './child-component.component.html',
  styleUrls: ['./child-component.component.css']
   })
   export class ChildComponentComponent implements OnInit {
  @Input() name;
  constructor() { }

  ngOnInit() {
  }
  }

Parent-component.html Code:

 <p>
  Parent Component
  </p>
  <app-child-component [name]="data"></app-child-component>
  <button>
  Send Money To Jack
  </button><br><br>
  
  <button>
  Send Money To Jill
  </button>

Parent-component.ts Code:

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

    @Component({
  selector: 'app-parent-component',
  templateUrl: './parent-component.component.html',
  styleUrls: ['./parent-component.component.css']
   })
   export class ParentComponentComponent implements OnInit {
  
  data={
  name1:'jack',
  Money1:10,
  name2:'Jill',
  Money2:'15'
  }
  constructor() { }

  ngOnInit() {
  }
  }

This is the whole code. And Below is the screenshot of output: 这是输出。我想要一些功能,当用户点击第一个按钮时,money1 变量增加 10,当用户点击第二个按钮时,money2 变量增加 10。 This is the output. i want some function that when user clicks on 1st Button then money1 variable gets increamented by 10 and when user clicks on second button then money2 variable gets increamented by 10.

That structure for displaying the data is not too good, and the scenario is somewhat sketchy, but if you're not going to change things atm, here you are:

add click functions to buttons:

<button (click)="incrementJack()">Send Money To Jack</button>

<button (click)="incrementJill()">Send Money To Jill</button>

define them in parent ts:

  incrementJack(){
    this.data.Money1 += 10;
  }

  incrementJill(){
    let amount = parseInt(this.data.Money2) + 10;
    this.data.Money2 = amount.toString();
  }

Note that the money1 is number and money2 is a string, so this cod is keeping their types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM