How to submit a form from another component angula

2020-07-24 03:49发布

问题:

I am stuck at something and I want your help.

I want to submit a form which is in another component and submit button is in another component.

How can I achieve that in angular 4?

This is my code's html.

Its form's html

    <form class="form form-validate" ngNativeValidate 
  (submit)="editInformationFunction($event)"
    #editForm="ngForm">
    <div class="row px-3 pb-3">

   <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 ">
    <!---------------Panel1 ------------------->
    <div class="panel panel-primary radius">
      <div class="panel-heading border-bottom p-2">
        <h3 class="panel-title m-0"><i class="fa fa-user green pl-3"> 
   </i> <span
          class="ml-2 font-weight-bold">PERSONAL INFORMATION</span> . 
   </h3>
        <span class="pull-right "><i class="glyphicon glyphicon- 
    chevron-down"> </i></span>
      </div>
      <div class="panel-body">

        <div class="row">

          <!--input fields-->

          <div class="col-xs-12 col-sm-12 col-md-12 col-md-6 col-lg-6 
    ">
            <div class="form-group mt-4 ml-4">
              <label for="name"><b>NAME<span class="text-danger ml-2">* 
    </span> </b></label>
              <input id="name" type="text" class="form-control"
                     [(ngModel)]="editInformationModel.name"
                     [ngModelOptions]="{standalone: true}" required>
            </div>
          </div>

          <div class="col-xs-12 col-sm-12 col-md-12 col-md-6 col-lg-6 
    ">
            <div class="form-group mt-4 mr-4">
              <label for="info"><b>BIRTH DATE
              </b></label>
              <input id="info" type="text" class="form-control"
                     [(ngModel)]="editInformationModel.birthdate ? 
     editInformationModel.birthdate : N/A "
                     [ngModelOptions]="{standalone: true}" required>
            </div>
          </div>

          <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
            <div class="form-group form-check-inline mt-1 ml-4">
              <b>GENDER<span class="text-danger ml-2">*</span></b>

              <div class="form-check-inline d-flex mt-1">

                 <label class="customradio"><span class="radiotextsty"> 
     <b>Male</b></span>
                  <input type="radio" checked="checked" name="radio"
                         [(ngModel)]="editInformationModel.sex"
                         [ngModelOptions]="{standalone: true}" 
   value="m">
                  <span class="checkmark"> </span>
                </label>
                <label class="customradio ml-2"><span 
    class="radiotextsty"><b>Female</b></span>
                  <input type="radio" name="radio"
                         [(ngModel)]="editInformationModel.sex"
                         [ngModelOptions]="{standalone: true}" 
    value="f">
                  <span class="checkmark"> </span>
                </label>

              </div>

            </div>
          </div>
</form>

Its forms .ts file

@Component({
selector: 'app-edit-information',
styleUrls: ['./edit-information.component.css'],
templateUrl: './edit-information.component.html'
})
export class EditInformationComponent implements OnInit { 
editInformationFunction(e) {
  console.log(this.editInformationModel);  
 this.editInformationService.editMemberInformation
 (this.editInformationModel).subscribe(
  response => {
    console.log(response);
    this.spinner.hide();
    if (response ['error'] == false) {
      console.log(response);
      this.toastr.success(response['data'], 
this.editInformationData.toastTitle.success);
    } else {
      this.spinner.hide();
      this.toastr.error(response['message'], 
this.editInformationData.toastTitle.error);
    }
  },
  err => {
    this.spinner.hide();
    this.toastr.error(err.error['message'], 
this.editInformationData.serverError);
    }
   )
  }
}

its my sidebar html from where i want to submit my form....

  <div class="d-flex" [hidden]="saveInformation">
  <button type="submit" class="btn btn-success btn-sm py-2 border-0"><i 
 class="fa fa-save"> </i>
    Save
    Information
  </button>
   <button class="btn btn-default btn-sm text-white ml-2 py-2" 
  routerLink="/household-information">
     Cancel
  </button>
  </div>

Its sidebar's .ts file

 @Component({
 selector: 'app-sidebar',
 styleUrls: ['./sidebar.component.css'],
templateUrl: './sidebar.component.html'
 })
export class SidebarComponent implements OnInit {}

回答1:

If your components are at time the easer way is using @Input and pass your component in a reference variable. e.g. You app.component is like

<hello #hello name="{{ name }}"></hello>
<nav-bar [component]="hello"></nav-bar>

//Your nav-bar is like

@Component({
  selector: 'nav-bar',
  template: `<button (click)="click()">click me</button>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class NavBarComponent  {
  @Input()component:any
  click()
  {
    console.log(this.component.variable)
  }
}

The "clasic" is use a service. Your service can be like

@Injectable()

export class DataService {

  private mySubjectSource = new Subject<any>();
  myObservable=this.mySubjectSource.asObservable();

  constructor(){}

  sendValue(value:any)
  {
    this.mySubjectSource.next(value);
  }
}

Then your component use this service:

The component that emit a value

export class NavBarComponent  {
  constructor(private service:DataService){}
  click2()
  {
    this.service.sendValue("save data")
  }
}

The component that receive the event

export class HelloComponent implements OnInit {
  constructor(private service:DataService){  }
  ngOnInit()
  {
    this.service.myObservable.subscribe(res=>{
      console.log(res);
    })
  }
}

in this stackblitz I put the two ways

Choose where you want to make the submit: In you nav getting the value of the form, or in the form when you emit a event from the nav-



回答2:

My understanding: 1) When you click 'Submit' in sidebar's HTML, you would like to execute the function 'editInformationFunction' in the form's ts file.

2) I don't see 'app-sidebar' being included in the form's HTML and so I assume they are siblings. So there is no direct parent-child relationship here.

3) editInformationModel - This is the key variable that you use inside the 'editInformationFunction'.

Solution: What you need is an 'event emitter'. It can easily solve your problem.

i) You can emit an event from your app-sidebar and catch it in your parent component (app-component.html, say)

ii) Then you can invoke the desired function in the form's ts file from the parent component.

This blog will help you. https://robferguson.org/blog/2017/08/31/angular-4-and-sibling-component-interaction/

I had a similar use case. This method worked 100% and was quite simpler.