繁体   English   中英

更新特定组件而不是整个页面

[英]Update Specific Component rather than whole page

我目前正在制作一个小应用程序,用户可以在其中将联系人添加到列表中。 我能够将联系人添加到列表中,它显示在一个单独的 div 中。 在我点击保存的那一刻,我有一些基本上等待的代码,整个应用程序都会刷新。 我目前遇到的问题是,当我为用户插入数据并单击“保存”时,它会刷新整个屏幕,但是当我单击“保存”时,我希望它只刷新联系人组件。

我目前有一段代码,它基本上刷新了所有组件,这没问题,但现在我想尝试刷新我也添加了数据的组件。

我已经包括以下代码:

`

<div class="container">

    <div class="main-contact-list">
        <h2>Contacts</h2>
        <li *ngFor="let contact of contacts;">
            <button type="button" (click)="getContact(contact.id)">
                <span class="name"> {{contact.firstName}} {{contact.lastName}}</span>
            </button>
        </li>
    </div>

    <div class="form">
        <form [formGroup]="fg">
            <div class="actionBtns">
                <button class="btn btn-primary" (click)="saveContact()">Edit/Save</button>
                <div class="divider"></div>
                <button class="btn btn-primary" (click)="deleteContact(contact.id)">Delete</button>
            </div>


            <div class="row" class="row-object">
                <input type="text" class="form-control" [(ngModel)]="contact.firstName" name="firstName"
                    formControlName="firstName" placeholder="First Name" />
                    
                <div class="divider"></div>

                <input type="text" class="form-control" [(ngModel)]="contact.lastName" name="lastName"
                    formControlName="lastName" placeholder="Last Name" />

                <div class="col">
                    <input type="text" class="form-control" [(ngModel)]="contact.emailAddress" name="emailAddress"
                        formControlName="emailAddress" placeholder="Email Address" />
                    <div class="divider"></div>
                    <input type="text" class="form-control" [(ngModel)]="contact.address1" name="address1"
                        formControlName="address1" placeholder="Address1" />
                    <div class="divider"></div>
                    <input type="text" class="form-control" [(ngModel)]="contact.address2" name="address2"
                        formControlName="address2" placeholder="Address2" />
                    <div class="divider"></div>
                    <input type="text" class="form-control" [(ngModel)]="contact.city" name="city"
                        formControlName="city" placeholder="City" />
                    <div class="divider"></div>
                    <input type="text" class="form-control" [(ngModel)]="contact.postCode" name="postCode"
                        formControlName="postCode" placeholder="Post Code" />
                    <div class="divider"></div>
                </div>

            </div>




        </form>

        <div class="activityForm" *ngIf="contact.id">
            <app-activities [childItem]="contact"></app-activities>
        </div>
    </div>

`

`

import { Component, OnInit } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
  FormsModule
} from '@angular/forms';
import { AppService } from '../app.service';

//interface for Contact
interface Contact {
  id?: number;
  firstName: string;
  lastName: string;
  emailAddress: string;
  address1: string;
  address2: string;
  city: string;
  postCode: string;
}

@Component({
  selector: 'app-contact-details',
  templateUrl: './contact-details.component.html',
  styleUrls: ['./contact-details.component.css'],
})
export class ContactDetailsComponent implements OnInit {
  constructor(private appService: AppService, private fb: FormBuilder) { }
  fg!: FormGroup;
  contacts: Contact[] = [];
  contact: any = {};

  //get the form field as a form control. it will useful for validation and etc
  get firstNameField(): FormControl {
    return this.fg.get('firstName') as FormControl;
  }

  get lastNameField(): FormControl {
    return this.fg.get('lastName') as FormControl;
  }

  get emailAddressField(): FormControl {
    return this.fg.get('emailAddress') as FormControl;
  }

  get address1Field(): FormControl {
    return this.fg.get('address1') as FormControl;
  }

  get address2Field(): FormControl {
    return this.fg.get('address2') as FormControl;
  }

  get postCodeField(): FormControl {
    return this.fg.get('postCode') as FormControl;
  }

  async ngOnInit() {
    this.initForm();
    this.getContacts();
  }

  //form init. here we create the reactive form. https://angular.io/guide/reactive-forms
  initForm(): void {
    let id = Date.now() * Math.random();
    this.fg = this.fb.group({
      id: [id],
      firstName: ['', [Validators.required]],
      lastName: ['', [Validators.required]],
      emailAddress: ['', [Validators.required, Validators.email]],
      address1: ['', [Validators.required]],
      address2: ['', [Validators.required]],
      city: ['', [Validators.required]],
      postCode: ['', [Validators.required]],
    });
  }

  //save function
  async saveContact() {
    console.log(this.fg);
    console.log(this.contact);

    //if form doesn't have any validation error this if condition will executed
    if (this.fg.valid) {

      const newContact: Contact = {
        firstName: this.fg.value.firstName,
        lastName: this.fg.value.lastName,
        emailAddress: this.fg.value.emailAddress,
        address1: this.fg.value.address1,
        address2: this.fg.value.address2,
        city: this.fg.value.city,
        postCode: this.fg.value.postCode,
      };
      if (this.contact?.id) {
        this.appService
          .editContacts(this.contact.id, newContact).subscribe();
      } else {
        this.appService
          .addContacts(newContact).subscribe();
      }
      this.fg.reset(); //resetting the form array
      await this.refresh();
    } else {
      console.log('this is invalid ');
    }
  }

  refresh(): void {
    window.location.reload();
  }

  async getContacts(): Promise<void> {
    await this.appService
      .getContacts()
      .subscribe((contacts: any) => (this.contacts = contacts));
  }

  edit(id: number): void {
    const data = this.contacts[id];
    this.fg.patchValue(data);
    this.refresh();
  }

  getContact(id: number | undefined) {
    this.appService
      .get(id)
      .subscribe((contact: any) => (this.contact = contact));
  }

  selectContact(contact: Contact) {
    this.contact = contact;
  }

  deleteContact(id: number | undefined) {
    this.appService.deleteContact(id).subscribe();
    this.refresh();
  }
}

`

我确实设法解决了这个问题。 大多数教程都说你基本上使用路由器路由,所以当发生某些事情刷新路由时,它应该显示新页面。

相反,我只是在我的数组和 object 前面添加了@Input。所以当在我的主要 html 页面中我使用 *ngFor 语句遍历数组时,每次更新它都会自动显示新列表

暂无
暂无

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

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