从 child 组件获取数据时如何更新 parent 组件视图?

How to update parent component view when data is fetched from child component?

我有一个 parent 和一个 child 组件,child 组件实际上是一个模式,我们可以在其中输入电子邮件并单击 'Add to List'。 然后使用@ViewChild 属性 从 parent 组件中获取输入的电子邮件。数组详细信息在 parent 中获得,因为我可以 console.log() 并从 parent.

中查看它们

但是如何使用收到的新数据更新 Parent 中的部分视图?

代码及说明如下:

Child分量:

"emails" 是一个包含电子邮件 ID 的数组。 我正在从 child.

获取这个数组
import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-add-student-popup',
  templateUrl: './add-student-popup.component.html',
  styleUrls: ['./add-student-popup.component.scss']
})


export class AddStudentPopupComponent implements OnInit {
  emails: string[] = [];
  constructor() { }

  ngOnInit(): void {

  }

  **** Some other code that adds user entered emails to an array 'emails' ****
  ----
  ----

  sendData() {
    console.log(this.emails);
  }

}

Parent

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

// Add students modal popup
import { BsModalRef, BsModalService } from  'ngx-bootstrap/modal/';
import { AddStudentPopupComponent } from './add-student-popup/add-student-popup.component';

@Component({
  selector: 'app-create-course',
  templateUrl: './create-course.component.html',
  styleUrls: ['./create-course.component.scss']
})

export class CreateCourseComponent implements OnInit, AfterViewInit {
  bsModalRef!: BsModalRef;
  emails: string[] = [];
  isEmpty: boolean = true;

  @ViewChild(AddStudentPopupComponent) addStudent!: AddStudentPopupComponent;

  constructor(private modalService: BsModalService) { }

  ngOnInit(): any {}

  ngAfterViewInit(): void {
    if (this.addStudent) {
      this.emails = this.addStudent.emails;
      isEmpty = false;
    }
  }

  openAddStudentModal() {
    this.bsModalRef = this.modalService.show(AddStudentPopupComponent, {class: 'modal-lg'});
    this.bsModalRef.content.closeBtnName = 'Close';
  }

}

我想在前端视图中使用更新后的“电子邮件”数组。使用此数组的视图部分应更新。

查看部分

填充并提交弹出窗口后,将填充电子邮件数组,它应该更新此视图部分。

<div class="multipleInput-container" *ngIf="!isEmpty;else noEmails">
    <div class="col-lg-12">
        <ul *ngFor="let email of emails">
            <li class="multipleInput-email">{{ email }}</li>
        </ul>
    </div>
</div>
<ng-template #noEmails>
    <div class="col-lg-3">
        <input type="text" class="form-control form-control-sm" 
            placeholder="No Students Added" aria-label="No Students Added">
    </div>
</ng-template>

提前致谢

你应该使用@Output

AddStudentPopupComponent

   emails: string[] = [];
   @Output() sendEmail = new EventEmitter();
   sendData() {
      this.sendEmail.emit(this.emails);
   }

然后在 create-course.component.html 文件中

<app-add-student-popup (sendEmail)="emails = $event"></app-add-student-popup>