2021年4月4日星期日

Pass value from input component to button component in Angular application

I'm trying to figure how to pass value from one Angular component to another my-input.component and my-button.component:

I'm trying to receive from my-input.component.ts and display @Input('name') with button (click)="displayReceivedValue()" from my-button.component.html in my-button.component.ts:

import { Component, Input, OnInit } from '@angular/core';  import { MyInput } from '../../interfaces/my-input';    @Component({    selector: 'app-my-button',    templateUrl: './my-button.component.html',    styleUrls: ['./my-button.component.scss'],  })  export class MyButtonComponent implements OnInit {    @Input('name')    public input!: MyInput;    constructor() {}      ngOnInit(): void {}      async displayReceivedValue() {      console.log('Received value: ', this.input);    }  }  

which is <app-my-button name=""></app-my-button> component in Login page login.component.html from my-input.component.ts with this.myValue from [(ngModel)]="myValue" in input of my-input.component.html, but I'm not sure, how to pass it to name="":

import { Component, EventEmitter, OnInit, Output } from '@angular/core';    @Component({    selector: 'app-my-input',    templateUrl: './my-input.component.html',    styleUrls: ['./my-input.component.scss'],  })  export class MyInputComponent implements OnInit {        public myValue: any;      constructor() {}      ngOnInit(): void {}  }  

Also I've tried use @Output() with <app-my-button (inputValue)="acceptData($event)"></app-my-button> component in Login page from my-input.component.ts:

import { Component, EventEmitter, OnInit, Output } from '@angular/core';            @Component({        selector: 'app-my-input',        templateUrl: './my-input.component.html',        styleUrls: ['./my-input.component.scss'],      })      export class MyInputComponent implements OnInit {        @Output() inputValue= new EventEmitter<string>();                  public myValue: any;          constructor() {}              ngOnInit(): void {             this.inputValue.emit(this.inputValue);        }      }  

in my-button.component.ts:

import { Component, Input, OnInit } from '@angular/core';    @Component({    selector: 'app-my-button',    templateUrl: './my-button.component.html',    styleUrls: ['./my-button.component.scss'],  })  export class MyButtonComponent implements OnInit {    constructor() {}    ngOnInit(): void {}    acceptData(data: any) {      console.log(data);    }  }  

I got nothing if I add (inputValue)="acceptData($event) to my-button.component.html, or if I add (inputValue)="acceptData($event) to login.component.html I got error:

TS2339: Property 'acceptData' does not exist on type 'LoginComponent'.

https://stackoverflow.com/questions/66946980/pass-value-from-input-component-to-button-component-in-angular-application April 05, 2021 at 08:19AM

没有评论:

发表评论