简体   繁体   English

在 angular 8 中动态添加嵌套组件

[英]dynamically add nested components in angular 8

I am building an angular 8 application.我正在构建一个 angular 8 应用程序。 I have a nested component which I would like to dynamically add on the parent component on clicking of a button on the parent component.我有一个嵌套组件,我想在单击父组件上的按钮时动态添加到父组件上。 Something like this below:下面是这样的: 在此处输入图片说明

The ADD button should add the component on the parent component. ADD 按钮应该在父组件上添加组件。 The close button should remove the nested component from the parent component.关闭按钮应该从父组件中删除嵌套组件。 Also, I would like communication between parent and nested component to happen on clicking some controls on the nested component, like clicking on the Add Student button etc. So far I have been able to create a nested component and add it on the parent component (not dynamic).此外,我希望在单击嵌套组件上的某些控件时发生父组件和嵌套组件之间的通信,例如单击“添加学生”按钮等。到目前为止,我已经能够创建一个嵌套组件并将其添加到父组件上(不是动态的)。

Please find the code below:请在下面找到代码:

add-student.component.html添加-student.component.html

<div class="col-lg-3 col-md-12">
  <div style="float: right;">
    <button type="button" class="close" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
    <button type="button" class="btn btn-primary">Add Student</button>
  </div>

I know that I can use jquery to dynamically add divs and achieve this.我知道我可以使用 jquery 来动态添加 div 并实现这一点。 But how can I achieve this using angular ?但是如何使用 angular 实现这一点? Is there a better and easier way to accomplish this ?有没有更好更简单的方法来实现这一目标?

Thanks谢谢

In angular think this way, you have a list of students and you want to add and remove them.以这种方式思考角度,您有一个学生列表,您想添加和删除它们。 components are presentation of data.组件是数据的表示。

Being said you need to do this据说你需要这样做

in parent component在父组件中

students: Array<Student> = [];

addStudent() {
 this.students = [...this.students, new Student()];
}

onRemoveStudent(student: Student) {
  const index = this.students.findIndex(student);
  if (index !== -1) {
     this.students.splice(index,1);
  }
}

<div *ngFor="let student of students">
  <app-student [student]="student" (remove)="onRemoveStudent($event)"></app-student>
</div>

in student component在学生组件中

@Input() student: Student;
@Output() remove: EventEmittrer<Student> = new EventEmittrer<Student>();

onRemoveButtonClick() {
  this.remove.emit(this.student);
}

You can achieve this by doing something like你可以通过做类似的事情来实现这一点

<button (click)="addComponent()"> ADD </button>
<div id="student-components">
   <student-list *ngFor="let component of components" [identifier]="component">

   </student-list>
</div>

components: string[] = [];
addComponent() {
   var id = ""; //generate something like Guid.NewGuid()
   this.components.push(id);
}

and in the add-student.component you can use the id to remove it from the parent component.在 add-student.component 中,您可以使用 id 将其从父组件中删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM