如何在Angular2中将数据从一个表单传递到另一个表单

时间:2018-03-05 09:10:44

标签: angular

我想将数据从一种形式传递到另一种形式。单击Form1的下一步按钮后,Form2应显示在Form1中输入的数据。怎么做到这一点..任何人都可以帮助我......谢谢你提前

Form1.component.html

<form [formGroup]="Form1" (ngSubmit)="saveNewCustomer(Form1.value)">
<label>Mobile No.</label>
<div class="form-group">
    <input class="form-control" name="MobileNo" placeholder="Mobile No" #MobileNo="ngModel" [(ngModel)]="CustomerForm.MobileNo">
</div>

<label>Name</label>
<div class="form-group">
    <input class="form-control" name="Name" placeholder="Name" #Name="ngModel" [(ngModel)]="CustomerForm.Name">
</div>

<label>Amount</label>
<div class="form-group">
    <input class="form-control" name="Amount" placeholder="Amount" #Amount="ngModel" [(ngModel)]="CustomerForm.Amount">
</div>

<div class="form-row">
    <div class="form-group col-md-8">
        <button type="submit" class="btn btn-lg btn-block btn-primary">Next</button>
    </div>
</div>

Form1.component.ts

export class Form1Component implements OnInit {
public CustomerForm: FormGroup;
public submitted: boolean;
FormValues: FormVM[] = [];
FormValue: FormVM;
constructor(private fb: FormBuilder, private router: Router, private dataService: AppDataService,) { }
ngOnInit() {
    this.CustomerForm = this.fb.group({
        MobileNo: [''],
        Name: [''],
        Amount: ['']
    });
}
saveNewCustomer(customer: FormVM) {      
    this.submitted = true; 
    this.router.navigate(['/Form2']);        
}

上面是Form 1组件代码,下面是Form 2组件代码,我应该在单击Form1的 Next 按钮后获得 的 Form2.component.html

    <h5>Form2</h5>
<form class="cat-form" *ngFor="let list of FormValues">
    <label>Mobile No.</label>
    <div class="form-group">
        <input class="form-control" name="MobileNo">
        {{list.MobileNo}}
    </div>

    <label>Name</label>
    <div class="form-group">
        <input class="form-control" name="Name">
        {{list.Name}}
    </div>

    <label>Amount</label>
    <div class="form-group">
        <input class="form-control" name="Amount">
        {{list.Amount}}
    </div>

</form>

Form2.component.ts

export class Form2Component {
    FormValues: FormVM[] = [];
    FormValue: FormVM;
    constructor(private dataService: AppDataService, private router: Router, private getdata: Form1Component) {
        getdata.FormValues;
    }
    ngOnInit() {

    }
}

1 个答案:

答案 0 :(得分:0)

您必须编写可以在各种组件之间共享的自定义服务,例如

<强> login.component.ts

import { Component } from '@angular/core';
import {ApiService} from './api.service';
import {AuthService} from './auth.service';
//import {ApiService} from './api.service';

@Component({
  selector: 'login',
  template: `
    <mat-card>
      <mat-card-header>
        <mat-card-title>
          Login New user
        </mat-card-title>
      </mat-card-header>
      <mat-card-content>
        <form>
          <mat-form-field class="example-full-width">
              <input [(ngModel)]="loginData.email" name="email" matInput placeholder="Email" value=""  type="email">
          </mat-form-field>
          <mat-form-field class="example-full-width">
                <input [(ngModel)]="loginData.password" name="password" matInput placeholder="Password" value="" type="password">
          </mat-form-field>
          <button (click)="post()" mat-raised-button color="primary">Login</button>
       </form>
     </mat-card-content>
   </mat-card>
  `
})
export class LoginComponent {
  constructor(private authService:AuthService){  }
  loginData={
  }
  //  mail:String;
  // password:String;
  //registerData={mail:string,password}

  post(){
    //console.log(this.registerData);
    this.authService.loginUser(this.loginData);//service to pass the login data 
  }
}

<强> register.component.ts

import { Component } from '@angular/core';
import {AuthService} from './auth.service';

//import {ApiService} from './api.service';

@Component({
  selector: 'register',
  templateUrl:'register.component.html'
})
export class RegisterComponent {
  constructor(private authService:AuthService){  }
  registerData={}

  //  mail:String;
  // password:String;
  //registerData={mail:string,password}

  post(){
    console.log(this.registerData);
    this.authService.registerUser(this.registerData);//authservice function
  }
}

<强> auth.service.ts

import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core'

@Injectable()
export class AuthService{
  messages=[];
  path='http://localhost:3000/auth';
  TOKEN_KEY='token';
  constructor(private http:HttpClient){}

  // getMessages(){
  //   this.http.get('http://localhost:3000/posts').subscribe(res =>{
  //     //console.log(res);
  //     this.messages=res.json();
  //   })
  // }
  get token(){
    return localStorage.getItem(this.TOKEN_KEY);
  }

  registerUser(registerData){

    this.http.post<any>(this.path+'/register',registerData).subscribe(res =>{
      this.messages=res;
    })
  }
  loginUser(loginData){

    this.http.post<any>(this.path+'/login',loginData).subscribe(res =>{
      console.log(res);
      localStorage.setItem(this.TOKEN_KEY,res.token);
      //this.messages=res.json();
    })
  }
}

<强> app.module.ts

    //some imports above//
    import {ApiService} from './api.service';
     @NgModule({
    declarations: [
      AppComponent,
      RegisterComponent,
      LoginComponent    
    ],
    imports: [
      BrowserModule,
      MatButtonModule,
      MatCardModule,
      MatToolbarModule,
      MatInputModule,
      BrowserAnimationsModule,
      FormsModule,
      MatListModule
    ],
    providers: [AuthService],//other services go inside providers array
    bootstrap: [AppComponent]
  })
  export class AppModule { }

基于上述代码的相同参考的简化plunkr示例 https://plnkr.co/edit/iWTGXE?p=preview