【发布时间】:2021-10-30 14:40:25
【问题描述】:
我有一个父组件和一个子组件,子组件实际上是一个模式,我们可以在其中输入电子邮件并单击“添加到列表”。 然后使用 @ViewChild 属性从父组件中获取输入的电子邮件。数组详细信息是在 parent 中获得的,因为我可以 console.log() 并从 parent 中查看它们。
但是如何使用收到的新数据更新 Parent 中的部分视图?
代码及解释如下:
子组件:
"emails" 是一个包含电子邮件 ID 的数组。 我正在从孩子那里获取这个数组。
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);
}
}
家长
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>
提前致谢
【问题讨论】:
标签: javascript angular typescript viewchild