简体   繁体   中英

Update Specific Component rather than whole page

I am currently making a small application where users can add contacts to a list. i am able to add the contacts to a list and it shows up in a separate div. at the moment when i click save, i have some code which basically has await and the whole app refreshes. the problem i am currently having is when i insert data for a user and click save it refreshes the whole screen but instead when i click save i want it to only refresh the contact component.

I currently have a piece of code which essentially refreshes all the components which is okay but now i want to try and just refresh the component i have added data too.

i have included the code below:

`

<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();
  }
}

`

I did manage to figure this problem out. Most tutorials were stating that you basically use the router route so when something happens to refresh the route and it should show the new page.

instead i just added @Input in front of my array and object. so when in my main html page i am using the *ngFor statement to iterate through the array, everytime it is updated it automatically shows the new list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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