Search code examples
angularcomponentsshare

How can I access data from child component without emiting it


enter image description hereSo like the picture discribes, The parent component is in blue and the red is the child component, so I want to type in some data in the input which is in the child component and when I click on the add answer button, i want to get the value from the input sent to the parent component. can anyone help me with that ?

I tried onchange event listener on the input so I can emit the value but it didnt work


Solution

  • https://angular.io/guide/inputs-outputs

    Event emitters are a fundamental Angular concept. The child has an EventEmitter which the parent listens to. To trigger an event on a button click in the child, your code should look similar to the following:

    <!-- parent template -->
    <my-child (myEvent)="handleMyEvent($event)"></my-child>
    
    
    // child component
    @Component({...}))
    export class MyChildComponent {
      
      @Output() myEvent = new EventEmitter<SomeType>()
      
      handleButtonClicked() {
        this.myEvent.emit(someValue)
      }
    
    <!--child template-->
    <button (click)="handleButtonClicked()>Some button</button>
    

    UPDATE:

    In this case, you'll need to store the contents of the input on the parent component, or access them at the time of add.

    your child component could have a listener on the input that emits the value of the input:

    <!-- child template -->
    <input (change)="emitChange($event)" type="text" />
    
    // child component
    @Output() myEvent = newEventEmitter<string>()
    emitChange(event: string) {
      this.myEvent.emit(event)
    }
    

    Your parent component's handleMyEvent function would need to manage storing the values emitted from the child component(s).