简体   繁体   中英

Passing Data from FORM to another component in Angular 2

1.After the data being entered , onClick of the submit button in nav.template.html.

2.FORM data should be passed into product.component.ts, Also the same data should be inserted inside the table in product.template.html.

3.In interface data types are being defined and passed through a service called product.data.js.

nav.component.ts

            import { Component } from '@angular/core';
            import { Router } from '@angular/router';
            import { FormBuilder, FormGroup, Validators } from '@angular/forms';

            @Component({
              moduleId: module.id,
              selector: 'ng-nav',
              inputs: ['products'],
              templateUrl: 'nav.template.html'
            })

            export class NavbarComponent {
              productForm: boolean=false;
              isNewForm: boolean;
              rForm : FormGroup;
              post : any;
              fname : string = '';
              lname : string = '';
              email : string = '';
              phnum : number;
              address : string = '';
              ZipCode : number;
              state : string = '';
              country : string = '';
              fnameAlert : string = 'Maximum 10 characters';
              lnameAlert : string = 'Maximum 10 characters';
              emailAlert : string = 'Maximum 50 characters in e-mail format';
              phnumAlert : string = 'Maximum 10 digits';
              addressAlert : string = 'Maximum 100 characters';
              ZipCodeAlert : string = 'Maximum 10 characters';

              constructor(private fb:FormBuilder){
                this.rForm = fb.group({
                  'fname':[null,Validators.compose([Validators.required,Validators.maxLength(10),Validators.minLength(3)])],
                  'lname':[null,Validators.compose([Validators.required,Validators.maxLength(10),Validators.minLength(3)])],
                  'email':[null,Validators.compose([Validators.required,Validators.maxLength(50)])],
                  'phnum':[null,Validators.compose([Validators.required,Validators.maxLength(10)])],
                  'address':[null,Validators.compose([Validators.required,Validators.maxLength(10)])],
                  'ZipCode':[null,Validators.compose([Validators.required,Validators.maxLength(6)])],
                  'state':[null,Validators.required],
                  'country':[null,Validators.required],
                  'validate' : ''
                });
              }
              addpost(post){
                this.fname = post.fname;
                this.lname = post.lname;
                this.email = post.email;
                this.phnum = post.phnum;
                this.address = post.address;
                this.ZipCode = post.ZipCode;
              }

              // saveProduct(product: Product){

              // }
            }

nav.template.html

        <button (click)="showAddProductForm()"><i class="fa fa-plus add-plus-button"></i></button>
        <div class="container">
            <form [formGroup]="rForm" (ngSubmit)="addPost(rForm.value)" *ngIf="productForm">
                <div class="form-container">
                    <div class="form-style-1">
                        <h2>Customer Details</h2>
                        <label>First Name<span class="required">*</span><input class="fname-holder" [(ngModel)]="newProduct.fname" type="text" formControlName="fname"/></label>
                        <div class="alert" *ngIf="!rForm.controls['fname'].valid && rForm.controls['fname'].touched">{{fnameAlert}}</div>
                        <label>Last Name<span class="required">*</span><input class="lname-holder" [(ngModel)]="newProduct.lname" type="text" formControlName="lname"/></label>
                        <div class="alert" *ngIf="!rForm.controls['lname'].valid && rForm.controls['lname'].touched">{{lnameAlert}}</div>
                        <label>Email <span class="required">*</span><input type="email" [(ngModel)]="newProduct.email" formControlName="email"/></label>
                        <div class="alert" *ngIf="!rForm.controls['email'].valid && rForm.controls['email'].touched">{{emailAlert}}</div>
                        <label>Phone <span class="required">*</span><input type="text" [(ngModel)]="newProduct.phnum" formControlName="phnum"/></label>
                        <div class="alert" *ngIf="!rForm.controls['phnum'].valid && rForm.controls['phnum'].touched">{{phnumAlert}}</div>
                        <label>Address <span class="required">*</span><textarea style="width: 319px;"type="address" [(ngModel)]="newProduct.id" formControlName="address"></textarea></label>
                        <div class="alert" *ngIf="!rForm.controls['address'].valid && rForm.controls['address'].touched">{{addressAlert}}</div>
                        <label>Zip Code <span class="required">*</span><input type="text" [(ngModel)]="newProduct.ZipCode" formControlName="ZipCode"/></label>
                        <div class="alert" *ngIf="!rForm.controls['ZipCode'].valid && rForm.controls['ZipCode'].touched">{{ZipCodeAlert}}</div>
                        <label>State <span class="required">*</span><input type="text" [(ngModel)]="newProduct.state" formControlName="state"/></label>
                        <label>Country <span class="required">*</span><input type="text" [(ngModel)]="newProduct.country" formControlName="country"/></label>
                        <input type="submit" style="width: 95px;" class="button button2" value="Submit" (click)="saveProduct(newProduct)" [disabled]="!rForm.valid"/> 
                    </div>
                </div>
            </form>
        </div>

product.component.ts

    import { Component, OnInit } from '@angular/core';
    import { Product} from './product';
    import { ProductService } from './product.service';

    @Component({
        moduleId: module.id,
        selector: 'ng-product',
        templateUrl: 'product.template.html'
    })

    export class ProductComponent implements OnInit{

    products:Product[];
    productForm:boolean = false;
    isNewForm:boolean;

    constructor (private _productService:ProductService){}

    ngOnInit(){
    this.getProducts();
    }

    getProducts(){
        this.products = this._productService.getProductsFromData();
            }

    removeProductForm(product: Product){
        this._productService.deleteProduct(product);
    }
    }

product.template.html

<div>
<div>
    <div style="float: right;"><input class="filter-search" placeholder="Search..." type="text" [(ngModel)]="term">
        <i class="fa fa-search search-bar-icon"></i>
      </div>
<table>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>Phone</th>
      <th>Address</th>
      <th>Zipcode</th>
      <th>State</th>
      <th>Country</th>
      <th></th>
      <th></th>
    </tr>
    <tr *ngFor="let product of products|filter:term">
      <td>{{product.fname}}</td>
      <td>{{product.lname}}</td>
      <td>{{product.email}}</td>
      <td>{{product.phnum}}</td>
      <td>{{product.address}}</td>
      <td>{{product.ZipCode}}</td>
      <td>{{product.state}}</td>
      <td>{{product.country}}</td>
      <td><i class="fa fa-edit" style="font-size:24px;color: #3eb0f7;" (click)="showEditProductForm(product)"></i></td>
      <td><i class="fa fa-trash" style="font-size:24px;color: #ff3232;" (click)="removeProductForm(product)"></i></td>
    </tr> 
  </table> 
</div>

</div>
<ng-nav [products]="products"></ng-nav>

product.service.ts

import{Injectable} from '@angular/core';
import{Product} from './product';
import{PRODUCT_ITEMS} from './product.data';


@Injectable()
export class ProductService {
    private pItems = PRODUCT_ITEMS;

    getProductsFromData():Product[]{
        console.log(this.pItems);
        return this.pItems

    }

    deleteProduct(product: Product){
        this.pItems.splice(this.pItems.indexOf(product),1)
    }
}

You can use Subject or BehaviourSubject from rxjs. Pass the submitted data to next method of Observable and subscribe it to another component and you will get the data there.

Your newProduct should exists in product.component.ts. By the magic of two way data binding you have the data in the component.

To send it to the service..

export class ProductComponent implements OnInit{

products:Product[];
newProduct: Product; 

constructor (private _productService:ProductService){}

ngOnInit(){
this.getProducts();
}

onSubmit(){
   this._productService.addProduct(this.newProduct);
}

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