1

I am building an angular 8 application. 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: enter image description here

The ADD button should add the component on the parent component. 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

<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. But how can I achieve this using angular ? Is there a better and easier way to accomplish this ?

Thanks

1
  • I would recommend taking the Angular tutorial angular.io/tutorial This is a great introduction to how Angular works. Your HTML should be driven by your model, which would be some array that is added to when the add button is clicked. Commented Mar 19, 2020 at 13:48

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.