简体   繁体   English

动态添加/删除HTML元素

[英]Adding/removing HTML elements dynamically

I have created an angular 8 app that allows a user to choose a date from a angular material date picker control. 我创建了一个angular 8应用程序,该应用程序允许用户从有角度的材质日期选择器控件中选择日期。 The app then sends a request a Mongodb using NodeJS to return a list of available daily sessions. 然后,该应用使用NodeJS发送一个Mongodb请求,以返回可用的每日会话列表。 This part of my app is working fine. 我的应用程序的这一部分工作正常。 The returned daily sessions are dynamically displayed as buttons in the html. 返回的每日会话会在html中动态显示为按钮。 My code iterates through the list of available sessions and creates a button in the html using a angular *ngFor loop. 我的代码遍历可用会话的列表,并使用有角的* ngFor循环在html中创建一个按钮。 My problem is that when the user then wants to choose another date from the date picker the new list of sessions is returned and the new list of available dates creates more buttons in the html using the *ngFor loop ie the new list of buttons is appended to the existing list of buttons. 我的问题是,当用户随后想要从日期选择器中选择另一个日期时,将返回新的会话列表,并且新的可用日期列表会使用* ngFor循环在html中创建更多按钮,即附加了新的按钮列表到现有的按钮列表。 What I actually want is the previously displayed button in the HTML to be deleted from the DOM and the new list of buttons for the newly selected date to be displayed in their place. 我真正想要的是从DOM中删除HTML中先前显示的按钮,并在其位置显示新选择的日期的新按钮列表。 Does anybody know how to do this? 有人知道怎么做这个吗? Thanks! 谢谢!

Below is my component ts file:- 以下是我的组件ts文件:-

import { Component, OnInit, ViewChild, ElementRef, Renderer2 } from '@angular/core';
import { Tank } from '../../models/tank.model';

import { FormGroup, FormControl } from '@angular/forms';
import * as moment from 'moment';
import { TankService } from 'src/app/services/tank.service';

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

export class BookingComponent implements OnInit {

  selectedDate: any;
  convertedDate: string;
  tankAvailability: Tank[];
  dateSelectionButtonPressed = false;
  tankOneAvailability: string[] = [];

  bookingForm: FormGroup;

  constructor(private tankService: TankService) { }

  ngOnInit(): void {
    this.bookingForm = new FormGroup({
       enteredDate: new FormControl(),
    });
  }

  onSelect(event) {
    this.selectedDate = event;

    this.convertedDate = moment(event).format('DD-MM-YYYY');
    this.bookingForm.patchValue({
      enteredDate: this.convertedDate
    });
  }

  getTankAvailabilityByDate() {
    this.dateSelectionButtonPressed = false;
    this.tankAvailability = [];
    if (this.convertedDate) {
      this.tankService.getTankAvailabilityByDate(this.convertedDate)
        .subscribe(tanks => {
          this.tankAvailability = tanks.tanks;
          this.populateAvailableSessions();
        });
    }
  }

  populateAvailableSessions() {
    this.dateSelectionButtonPressed = true;
    for(let i = 0; i < this.tankAvailability.length; i++) {
      if (this.tankAvailability[i].tankNumber === 1) {
          console.log(this.tankAvailability[i]);
          if (this.tankAvailability[i].sessionOne === false) {
            this.tankOneAvailability.push('07:00');
          }
          if (this.tankAvailability[i].sessionTwo === false) {
            this.tankOneAvailability.push('09:00');
          }
          if (this.tankAvailability[i].sessionThree === false) {
            this.tankOneAvailability.push('11:00');
          }
          if (this.tankAvailability[i].sessionFour === false) {
            this.tankOneAvailability.push('13:00');
          }
          if (this.tankAvailability[i].sessionFive === false) {
            this.tankOneAvailability.push('15:00');
          }
          console.log(this.tankOneAvailability);
        }
      }
  }
}

Below is my component HTML file:- 以下是我的组件HTML文件:-

<mat-card>
  <div class="center-section">
    <h1>Book a float</h1>

    <p>
      Select a date on the calendar below and we will display all the available float times
    </p>

    <form (submit)="getTankAvailabilityByDate()" [formGroup]="bookingForm">
      <div class="calendar-wrapper">
        <mat-calendar [selected]="selectedDate" (selectedChange)="onSelect($event)"></mat-calendar>
      </div>
      <mat-form-field class="invisible-field">
        <input matInput formControlName="enteredDate">
      </mat-form-field>
      <button mat-raised-button color="primary" type="submit">Get availability</button>
    </form>
  </div>
</mat-card>

<mat-card *ngIf="dateSelectionButtonPressed">
    <mat-card-header>
        <mat-card-title>Tank 1</mat-card-title>
    </mat-card-header>
    <mat-card-content *ngFor="let session of tankOneAvailability">
       <button mat-raised-button color="primary">{{session}}</button>
    </mat-card-content>
</mat-card>

You would need to empty the array to show new list of buttons. 您需要清空数组以显示新的按钮列表。 Below code needs to be changed 下面的代码需要更改

populateAvailableSessions() {
    this.dateSelectionButtonPressed = true;
    // always create new array so new values are pushed
    this.tankOneAvailability = []; 
    for(let i = 0; i < this.tankAvailability.length; i++) {
      if (this.tankAvailability[i].tankNumber === 1) {
          console.log(this.tankAvailability[i]);
          if (this.tankAvailability[i].sessionOne === false) {
            this.tankOneAvailability.push('07:00');
          }
          if (this.tankAvailability[i].sessionTwo === false) {
            this.tankOneAvailability.push('09:00');
          }
          if (this.tankAvailability[i].sessionThree === false) {
            this.tankOneAvailability.push('11:00');
          }
          if (this.tankAvailability[i].sessionFour === false) {
            this.tankOneAvailability.push('13:00');
          }
          if (this.tankAvailability[i].sessionFive === false) {
            this.tankOneAvailability.push('15:00');
          }
          console.log(this.tankOneAvailability);
        }
      }
  }

Hope this helps. 希望这可以帮助。

You need to reinitialise the tankOneAvailability array each time you run a new query like you do for the tankAvailability (currently you keep pushing more values into it) 你需要重新初始化tankOneAvailability像你这样的做每次运行一个新的查询时间序列tankAvailability (目前持续推动更值了进去)

ie

 getTankAvailabilityByDate() {
    this.dateSelectionButtonPressed = false;
    this.tankAvailability = [];
    this.tankOneAvailability = []

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

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