从父级调用时获取子表单数据

时间:2017-02-21 06:45:29

标签: forms angular typescript call

您好我对Angular 2有疑问,真的不知道怎么做,我需要你的帮助:)。

我有一个子组件,它具有简单的注册表单,但父模板上的提交按钮。因此,当我按下提交按钮时,它将从子组件表单中获取数据。

这是我的例子。

父组件ts

import {Component, ViewChild, OnDestroy, Output, EventEmitter} from '@angular/core';
import {GlobalEvent} from 'app/shared/GlobalEvent';


@Component({
    selector: 'signup',
    templateUrl: 'SignUpModalComponent.html',
    styleUrls: ['SignUpModalComponent.scss'],
})

export class SignUpModalComponent implements OnDestroy {
    public overlayState: boolean;
    public step: number = 1;
    public formSubmit: boolean;

    @ViewChild('firstModal')
    modal: any;

    constructor(private modalEventService: GlobalEvent) {
        this.modalEventService.modalChangeEvent.subscribe((res: boolean) => {
            this.overlayState = res;
            if (res) {
                this.modal.open();
            } else {
                this.modal.close();
            }
        });
    }

    closeModal(value: boolean): void {
        this.modalEventService.close(false);
        this.modal.close()
    }

    ngOnDestroy() {
        this.modalEventService.modalChangeEvent.unsubscribe();
    }

    incrementStep():void {
        this.step += 1;
    }

    decrementStep():void {
        this.step -= 1;
    }

    onFormSubmit(): void {
        this.formSubmit = true;
    }
}

父组件html模板

<div class="modal-overlay" *ngIf="overlayState"></div>
<modal (onClose)="closeModal(false)" #firstModal >
    <modal-header>
        <button (click)="firstModal.close()" class="close-btn"><i class="material-icons">close</i></button>
        <div class="steps-container">
            <span [ngClass]="{'active': step == 1 }">1</span>
            <span [ngClass]="{'active': step == 2 }">2</span>
            <span [ngClass]="{'active': step == 3 }">3</span>
            <span [ngClass]="{'active': step == 4 }">4</span>
        </div>
    </modal-header>
    <modal-content>
        <signup-form [hidden]="step != 1" [formSubmit]="formSubmit"></signup-form>
        <signup-social ngClass="social-step{{step}}" [step]="step"></signup-social>
    </modal-content>
    <modal-footer>
        <button md-button (click)="decrementStep()" [hidden]="step == 1"><Back</button>

        <button md-button (click)="incrementStep(); onFormSubmit()"  [hidden]="step != 1">Next></button>

        <button md-button (click)="incrementStep()"  [hidden]="step == 1 || step == 4">Skip</button>
    </modal-footer>
</modal>

子组件ts文件

import {Component, OnInit, Input} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {CustomValidators} from 'ng2-validation';


import {SignUpFormInterface} from './SignUpFormInterface';

@Component({
    selector: 'signup-form',
    templateUrl: 'SignUpForm.html',
    styleUrls: ['SignUpForm.scss']
})


export class SignUpForm implements OnInit {
    signupInfo: FormGroup;
    public tmppass: any;

    @Input() set formSubmit(sendData: boolean) {
        if (sendData) {

        }
    }

    constructor(private formbuilder: FormBuilder) {
    }

    ngOnInit() {

        this.signupInfo = this.formbuilder.group({
            email: ['', [CustomValidators.email]],
            username: ['', [Validators.required, CustomValidators.min(10)]],
            password: ['', [Validators.required, CustomValidators.rangeLength([5, 100]), this.setPass]],
            confirmPassword: ['', [Validators.required, CustomValidators.rangeLength([5, 100]), CustomValidators.equal(this.tmppass)]],
            fullName: ['', [Validators.required, CustomValidators.min(10)]],
            gender: ['', [Validators.required]],
            countrys: ['', [Validators.required]],
        });
    }

    setPass(c: any): void {
        console.log('sdsd', c.value);
        if (c.value) {
            this.tmppass = '';
            this.tmppass = <string>c.value;
        }
    }


    onSubmit({value, valid}: {value: SignUpFormInterface, valid: boolean}) {
        console.log(this.signupInfo);
    }

    cons() {
        console.log(this.signupInfo);
    }
}

function validateEmail(c: any) {
    let EMAIL_REGEXP = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    return EMAIL_REGEXP.test(c.value) ? c.email = false : c.email = true;

}

子组件html模板

<div class="sign-up-form clearfix">
    <form novalidate (ngSubmit)="onSubmit(signupInfo)" [formGroup]="signupInfo">
        <label>
            <input type="file" placeholder="Last Name*" name="lastName"/>
            upload an avatar
        </label>

        <md-input-container>
            <input md-input placeholder="Email address*" name="email" formControlName="email"/>
        </md-input-container>
        <!--<p *ngIf="signupInfo.controls.email.errors?.email">error message</p>-->
        <div class="errror-msg" *ngIf="signupInfo.controls.email.errors?.email">
            <md-hint>
                <span>Name should be minimum 6 characters</span>
            </md-hint>
        </div>
        <p *ngIf="signupInfo.controls.username.errors?.min">error message</p>
        <div class="input-wrap" [ngClass]="{'error': signupInfo.controls.username.errors?.min}">
            <md-input-container>
                <input md-input placeholder="Username*" name="username" formControlName="username"/>
            </md-input-container>
            <div class="errror-msg" *ngIf="signupInfo.controls.username.errors?.min">
                <md-hint>
                    <span>Name should be minimum 6 characters</span>
                </md-hint>
            </div>

            <div class="errror-msg"
                 *ngIf="signupInfo.get('username').hasError('minlength') && signupInfo.get('username').touched">
                <md-hint>
                    <span>Name should be minimum 6 characters</span>
                </md-hint>
            </div>
        </div>
        <p *ngIf="signupInfo.controls.password.errors?.rangeLength">error xcdfdfd</p>
        <md-input-container>
            <input md-input placeholder="Password*" formControlName="password"/>
        </md-input-container>

        <p *ngIf="signupInfo.controls.confirmPassword.errors?.rangeLength">error password</p>
        <p *ngIf="signupInfo.controls.confirmPassword.errors?.equal">error equal</p>

        <md-input-container>
            <input md-input placeholder="Confirm Password*" formControlName="confirmPassword"/>
        </md-input-container>

        <p *ngIf="signupInfo.controls.fullName.errors?.min">error password</p>
        <md-input-container>
            <input md-input placeholder="Full Name*" name="fullName" formControlName="fullName"/>
        </md-input-container>

        <p *ngIf="signupInfo.controls.gender.errors?.required">error password</p>
        <md-select placeholder="Gender" formControlName="gender">
            <md-option *ngFor="let food of ['react','angular']" [value]="food">
                {{ food }}
            </md-option>
        </md-select>
        <p *ngIf="signupInfo.controls.countrys.errors?.required">error password</p>
        <md-select placeholder="Country" formControlName="countrys">
            <md-option *ngFor="let country of countrys" [value]="country">
                {{ country.name }}
            </md-option>
        </md-select>
        <div class="input-wrap">
            <md-input-container placeholder="Date of Birth *">
                <input md-input placeholder="mm/dd/yyyy" type="text" name="DateofBirth"/>
            </md-input-container>
        </div>
    </form>
</div>

感谢您的帮助:)

0 个答案:

没有答案