Angular-在ng-template中单击“提交”按钮时,表单提交不会触发

时间:2018-07-03 13:42:41

标签: angular forms

我有一个父组件模板,其中定义了选项卡的基本html和用于呈现每个选项卡内容的router-outlet。每个标签都定义了其组件和关联的路由。

我将在每个选项卡中都有表单,我想在选项卡上方设置诸如保存,取消等操作按钮。为此,我在父组件中定义了ngTemplateOutlet并将其设置为从路由组件属性中设置的组件属性。

ParentComponent.ts

export class ParentComponent implements OnInit {
  actionButtonTemplateRef: TemplateRef<any>;
  constructor() { }

  ngOnInit() {
  }
  onActivate(componentRef) {
    this.actionButtonTemplateRef= componentRef.actionButtonsTemplate;
  }
}

ParentComponent.html

<div class="panel panel-white panel-height">
   <div class="panel-body">

      <ng-container *ngTemplateOutlet="actionButtonTemplateRef">
      </ng-container>

       <div role="tabpanel">
          <!-- Nav tabs -->
            <ul class="nav nav-tabs" role="tablist">
              <li role="presentation" routerLinkActive="active">
                <a [routerLink]="['profile']" role="tab">
                  <i class="icon-users"></i> Profile</a>
              </li>

              <li role="presentation" routerLinkActive="active">
                <a [routerLink]="['invite-user']" role="tab">
                  <i class="icon-envelope"></i> Invite Users</a>
              </li>
            </ul>
            <!-- Tab panes -->
            <div class="tab-content m-t-sm">
              <div role="tabpanel" class="tab-pane active fade in">
                <router-outlet
                (activate)="onActivate($event)"></router-outlet>
              </div>
            </div>
          </div>
       </div>
    </div>

ChildRoutedComponent.ts

export class ChildRoutedComponent {

  model: any;
  @ViewChild('actionButtonsTemplate') actionButtonsTemplate: TemplateRef<any>;

  constructor() { }


  submit(): void {
    //toDO
  }
}

ChildRoutedComponent.html

<form #form="ngForm" class="form-horizontal" (ngSubmit)="submit()">
    <ng-template #actionButtonsTemplate>

        <div class="row">
            <div class="col-md-12">
              <div class="pull-right btn-toolbar">
                <button type="submit" class="btn btn-primary btn-rounded" [disabled]="form.invalid">Save</button>
                <a class="btn btn-default btn-rounded" [routerLink]="['/']">Cancel</a>
              </div>
            </div>
          </div>
        </ng-template>
  <br />
  <div class="row">
    <div class="col-md-10">

      <div class="form-group" [ngClass]="{'has-error' : name.touched && name.errors?.required}">
        <label for="inputEmail3" class="col-sm-2 control-label">Name
            <span>*</span>
        </label>

        <div class="col-sm-10">
          <input class="form-control" placeholder="Name" name="name" required [(ngModel)]="model.name" #name="ngModel" />
        </div>
      </div>

    </div>
  </div>

</form>

所有内容均可在ui上正确呈现。保存按钮可以根据表单有效性正确地切换其状态。但我看到一个问题,当我点击“保存”按钮时,它不会触发form提交。为什么?

0 个答案:

没有答案