简体   繁体   中英

How can I pass data on button click from one component to another using Angular 8?

I'm trying to pass the data from one component to another and I'd like it to happen on the button click. Not sure how to set this up. I've marked my properties with @Output() and @Input() and set up the passing using the app properties setup, but would like this to happen when the button is clicked.

In my question.component.html, this is the button I have created:

 <div class="viewResultsNav" *ngIf="question && question.questionId === 
   totalQuestions">
   <button type="button" (click)="navigateToResults();">
     View Your Results
   </button>
 </div>

and I have a template where I'm passing to app-results:

 <ng-template #quiz_results>
   <app-results
     [allQuestions]="allQuestions"
     [totalQuestions]="totalQuestions"
     [totalQuestionsAttempted]="totalQuestionsAttempted"
     [correctAnswers]="correctAnswers"
     [progressValue]="progressValue"
     [percentage]="percentage">
   </app-results>
 </ng-template>

In the child component, all these properties are marked with @Input(), so I'd like these properties to get passed via the button into the component. Right now if I click the button it's navigating to ResultsComponent but it doesn't pass any data. Is it possible to pass data along with the router or can the ng-template quiz_results be served from the button?

Try something like this:

app-parent.ts:

receivedChildMessage: string;
getMessage(message: string) {
    this.receivedChildMessage = message;
}

app-parent.html

<app-child (messageToEmit)="getMessage($event)"></app-child>  

app-child.ts:

@Output() messageToEmit = new EventEmitter<string>();

sendMessageToParent(message: string) {
    this.messageToEmit.emit(message)
}

app-child.html:

<button (click)="sendMessageToParent(messageToSendC)">Send to Parent</button>

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