当子表单变脏时,从父组件访问子组件

时间:2017-06-07 10:16:02

标签: javascript angular typescript angular2-routing angular2-forms

我创建了一个挂起的更改警卫,警告我的用户,如果对表单进行了更改并在导航之前发出警告。

这一切都很好但我在页面上有一个使用选择器渲染的子组件,该组件也有一个表单。

如何从我的警卫处获取此表格以检查表格是否脏?

后卫:

import { CanDeactivate } from '@angular/router';
import { FormGroup } from '@angular/forms';
import { DialogService } from "ng2-bootstrap-modal";
import { ConfirmComponent } from '../components/confirm/confirm.component';
import { Inject } from '@angular/core';

export interface FormComponent {
    form: FormGroup;
}

export class PreventUnsavedChangesGuard implements CanDeactivate<FormComponent> {

constructor(@Inject(DialogService) private dialogService: DialogService) { }

canDeactivate(component: FormComponent): Promise<boolean> {

    if (component.form.dirty) {
        return new Promise<boolean>((resolve, reject) => {

            this.dialogService.addDialog(ConfirmComponent, {
                title: 'Unsaved Changes',
                message: 'You have unsaved changes. Are you sure you want to navigate away?'
            })
                .subscribe((isConfirmed) => {
                    return resolve(isConfirmed);
                });
        });
    }

    return Promise.resolve(true);
    }
}

1 个答案:

答案 0 :(得分:2)

将父表单作为输入传递给子组件。然后子组件需要将输入字段绑定到该表单。如果孩子的输入字段变脏,那么父表单将变脏。因此,您不需要在警卫中访问子表单。例如,

父组件ts

<child-component
   [parentForm]="parentComponentForm"
</child-component>

父组件的HTML

export class ChildComponent implements OnInit {
   @Input() parentForm: FormGroup;      
   let inputFieldControl = new FormControl('', Validators.required);
   this.parentForm.addControl(this.inputFieldControlName, inputFieldControl);
}

子组件ts

<input type="text" class="form-control" [formControl]="parentForm.controls[inputFieldControlName]">

子组件的HTML

declare @x xml = '<MultiNodePicker type="content">
  <nodeId>5713</nodeId>
  <nodeId>6817</nodeId>
  <nodeId>5424</nodeId>
  <nodeId>1888</nodeId>
  <nodeId>6128</nodeId>
  <nodeId>6339</nodeId>
</MultiNodePicker>'

Select Stuff(( Select ','+ y.value(N'text()[1]', N'nvarchar(MAX)')
FROM @x.nodes(N'MultiNodePicker/nodeId') as x(y) for xml path('') ),1,1,'')