将数据从父级传递给子级(嵌套表单)

时间:2017-03-29 15:15:23

标签: javascript angular input angular2-forms

我正在创建一个嵌套表单,其中我有父组件,其中包含表单并具有提交按钮。而儿童组件就是形式本身。

当我提交表单时,属性submitted变为true,我需要在提交时告知我的子组件submitted现在是true

这是父组件中提交按钮的代码:

      enviarDados(model: dadosAcordo, isValid: boolean, isJuridica:boolean) {
        this.servError = "";
        this.submitted = true; 
        //more code
       }

这就是到目前为止子组件的样子:

export class TitularComponent implements OnChanges {
  @Input('group') // this is the input for the form
  @Input('submitted') // input for the status of submit
  public titularForm: FormGroup;
  @Output() modelChanged = new EventEmitter();


  constructor(private _fb: FormBuilder, private finalizaAcordo:FinalizaNegociacaoService) {} 

  ngOnChanges(){

  }
// more code

这是父组件上的html:

<div class="wrap-acordo">
  <form [formGroup]="formDadosBancarios" novalidate class="" (ngSubmit)="enviarDados(formDadosBancarios.value)">
      <div formArrayName="dados_titular">
        <div *ngFor="let dados_titular of formDadosBancarios.controls.dados_titular.controls; let i=index">
          <div [formGroupName]="i">
            <div class="col s12" *ngIf="formDadosBancarios.controls.dados_titular.length > 1">
              <span class="span-removeTitular right-align" (click)="removeTitular(i)"> Remover {{i+1}}º Titular </span>
            </div>
            <titular (modelChanged)="recebeValidators($event)" [group]="formDadosBancarios.controls.dados_titular.controls[i]"></titular>
          </div>
        </div>
      </div>
      <div class="col s12 m6">
        <input type="submit" class="botao-medio btn-aceita" value="Aceitar">
      </div>
      <div class="col s12 m6">
        <input type="button" class="botao-medio btn-recusa" value="Recusar">
      </div>
    </div>
  </form>
</div>

有人能帮助我吗?谢谢:))

1 个答案:

答案 0 :(得分:1)

在父组件中,单击该按钮时,请设置this.formsubmitted = true。在子cmponent中,使用@Input将此表单设置为输入。如果你需要在formubmitted变为true时输入dp,那么对输入的formsubmitted使用ngonchanges。 Ngonchanges(更改:Simplechange){ if(更改[&#39;已提交&#39;]&amp;&amp;更改[&#39;已提交&#39;]。currentvalue){ 做你的东西在这里 } }

您可以参考https://angular.io/docs/ts/latest/api/core/index/OnChanges-class.html