簡體   English   中英

將數據從FORM傳遞到Angular 2中的另一個組件

[英]Passing Data from FORM to another component in Angular 2

1.輸入數據后,單擊nav.template.html中的提交按鈕。

2.FORM數據應傳遞到product.component.ts中,同樣的數據也應插入product.template.html中的表中。

3.在接口中,數據類型正在定義並通過名為product.data.js的服務傳遞。

導航組件

            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>

產品服務

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

您可以從rxjs使用Subject或BehaviourSubject。 將提交的數據傳遞給Observable的下一個方法,並將其訂閱到另一個組件,您將在那里獲得數據。

您的newProduct應該存在於product.component.ts中。 通過雙向數據綁定的魔力,您可以在組件中擁有數據。

將其發送到服務。

export class ProductComponent implements OnInit{

products:Product[];
newProduct: Product; 

constructor (private _productService:ProductService){}

ngOnInit(){
this.getProducts();
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM