Skip to content
Advertisement

Angular: Add component by clicking checkbox and delete component by unclicking it

I am new to angular and am currently working on a ticket booking system. There, I need to add passengers according to the needs of the user. In the booking component, there is a form component where passenger details are entered.

I want to add a button(add another passenger) in the form component such that when it is clicked, the application generates another form component for the user to add another passenger’s details.

Along with the passenger add button, I am thinking of adding a passenger remove button that removes the passenger and the corresponding forms component. I don’t want the new component to be a child of the previous forms component so that in case, if we have total of 5 passengers and I delete the passenger 2, that does not delete all the passengers from 2 to 5.

booking.component.html

<form id="bookingForm">
    <label for="pName">Passenger Name:</label>
    <input type="text" id="pName" name="pName"><br><br>
    <label for="age">Age:</label>
    <input type="text" id="age" name="age"><br><br>
    <label for="addPassenger"> Add Passenger</label><br>
    <input type="checkbox" id="addPassenger" name="addPassenger" value={{passengerCount}}>
    <button (click)="addPassenger()">Add Passenger</button>
    <button (click)="removePassenger()">Remove Passenger</button>
</form>

<input type="submit" value="Confirm" form="bookingForm">



Advertisement

Answer

You will need to make a function in your component that add or remove new passenger from array of passengers.

In HTML, you will use ngFor to add new passenger in your form.

You can see it done here

Angular 6 Dynamically Add Rows Reactive Forms

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement