【问题标题】:How to submit a form from another component angular 4?如何从另一个组件 Angular 4 提交表单?
【发布时间】:2019-05-16 23:38:31
【问题描述】:

我遇到了一些问题,我需要你的帮助。

我想提交一个在另一个组件中的表单,而提交按钮在另一个组件中。

如何在 Angular 4 中实现这一点?

这是我的代码的 html。

它的表单的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>

其形式为 .ts 文件

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

它是我要提交表单的侧边栏 html....

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

其侧边栏的 .ts 文件

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

【问题讨论】:

    标签: javascript html angular forms


    【解决方案1】:

    如果您的组件有时使用更简单的方法是使用 @Input 并将您的组件传递到引用变量中。 例如 你的 app.component 就像

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

    //你的导航栏是这样的

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

    “经典”是使用服务。你的服务可以像

    @Injectable()
    
    export class DataService {
    
      private mySubjectSource = new Subject<any>();
      myObservable=this.mySubjectSource.asObservable();
    
      constructor(){}
    
      sendValue(value:any)
      {
        this.mySubjectSource.next(value);
      }
    }
    

    那么你的组件使用这个服务:

    发出值的组件

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

    接收事件的组件

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

    this stackblitz我放了两种方式

    选择您要提交的位置:在导航中获取表单的值,或者在您从导航发出事件时在表单中-

    【讨论】:

    • 它可以与表单一起使用吗?比如我们必须在哪里提交函数?
    • Usman,如果您选择调用具有表单的组件中的服务,则您订阅了组件,并且在订阅中,您可以调用组件的任何功能。如果您选择在导航栏中调用服务,您将在 component.editInformationModel.value 中获得表单的值
    • 我应用了此代码,但我的表单提交了多次,这意味着我在第 1 次第 2 次第 4 次获得成功消息等等我不知道为什么@Eliseo
    • 当使用 getter 时,Angular 在组件的生命周期内多次执行 getter。这是因为我们必须小心使用。如果它是关于恢复变量的值或类似的东西,那并不重要。如果您使用了不应该发生的主题
    • 你能看到我关于这个主题的最新帖子吗? @Eliseo stackoverflow.com/questions/54062969/…
    【解决方案2】:

    我的理解: 1) 当您点击侧边栏 HTML 中的“提交”时,您希望在表单的 ts 文件中执行函数“editInformationFunction”。

    2) 我没有看到表单的 HTML 中包含“app-sidebar”,因此我认为它们是兄弟姐妹。所以这里没有直接的父子关系。

    3) editInformationModel - 这是您在“editInformationFunction”中使用的关键变量。

    解决方案: 您需要的是一个“事件发射器”。它可以轻松解决您的问题。

    i) 你可以从你的应用侧边栏发出一个事件并在你的父组件中捕获它(app-component.html,比如说)

    ii) 然后您可以从父组件调用表单的 ts 文件中所需的函数。

    这个博客会帮助你。 https://robferguson.org/blog/2017/08/31/angular-4-and-sibling-component-interaction/

    我有一个类似的用例。这种方法 100% 有效,而且相当简单。

    【讨论】:

    • 谢谢兄弟 :) 我会阅读该博客,顺便说一句 包含在 html 表单中
    • 欢迎。但是,当我在 HTML 表单中执行 Ctrl+F 时,此处发布的代码没有该应用程序选择器。好吧,如果 app-sidebar 是表单的子项,那么您可以使用 Eliseo 提到的 @Input 绑定。​​
    猜你喜欢
    • 2022-12-22
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多