Angular 5 Parent and Child Communication - PullRequest
0 голосов
/ 02 мая 2018

Я хочу создать компоненты для Create & Edit, но он имеет ту же форму, поэтому я создаю форму в другом компоненте.

вот код:

Родитель: OrganizationEditComponent (я заполняю данные организации с помощью распознавателя)

import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { AlertifyService } from './../../_services/alertify.service';
import { Organization } from './../../_models/organization';
import { OrganizationService } from './../../_services/organization.service';


@Component({
  selector: 'app-organization-edit',
  templateUrl: './organization-edit.component.html',
  styleUrls: ['./organization-edit.component.css']
})
export class OrganizationEditComponent implements OnInit {
    org: Organization;
    editForm: FormGroup; 

  constructor(private orgService: OrganizationService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router, 
    private alertify: AlertifyService) { }

  ngOnInit() {
    this.route.data.subscribe( data => {
        this.org = data['organization'];
    });
  }

  }


}

OrganizationEditComponent.html

<h1>Children </h1> 
<app-organization-form [org]="org"></app-organization-form>

Детский компонент: OrganizationFormComponent.ts

import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { AlertifyService } from './../../_services/alertify.service';
import { Organization } from './../../_models/organization';
import { OrganizationService } from './../../_services/organization.service';


@Component({
  selector: 'app-organization-form',
  templateUrl: './organization-form.component.html',
  styleUrls: ['./organization-form.component.css']
})
export class OrganizationFormComponent implements OnInit {
    @Input() org: Organization;
    myForm: FormGroup;

  constructor(private orgService: OrganizationService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private alertify: AlertifyService
    ) { }

  ngOnInit() {
      this.createForm();
  }

  createForm() {
    this.myForm = this.fb.group({
        organizationName: [this.org.organizationName, Validators.required],
        legalName: [this.org.legalName, Validators.required],
        logoUrl: [this.org.logoUrl, Validators.required],
        abn: [this.org.abn, Validators.required],
        acn: [this.org.acn, Validators.required]
    });    
  }

  save() {

  }
}

OrganizationFormComponent.html

{{org |json}}

<div class="container">
    <div class="row">
        <form [formGroup]="myForm" (ngSubmit)="save()" class="form-horizontal">

            <div class="form-group" [ngClass]="{'has-error': editForm.get('organizationName').touched && editForm.get('organizationName').hasError('required')}">
              <label class="col-sm-2" for="organizationName">organizationName</label>
              <div class="col-sm-7">
                <input class="form-control" placeholder="organizationName" formControlName="organizationName">
                <span class="help-block" *ngIf="editForm.get('organizationName').touched && editForm.get('organizationName').hasError('required')">organizationName is required</span>
              </div>
            </div>
            <div class="form-group" [ngClass]="{'has-error': editForm.get('legalName').touched && editForm.get('legalName').hasError('required')}">
              <label class="col-sm-2" for="legalName">legalName</label>
              <div class="col-sm-7">
                <input class="form-control" placeholder="legalName" formControlName="legalName">
                <span class="help-block" *ngIf="editForm.get('legalName').touched && editForm.get('legalName').hasError('required')">legalName is required</span>
              </div>
            </div>
            <div class="form-group" [ngClass]="{'has-error': editForm.get('logoUrl').touched && editForm.get('logoUrl').hasError('required')}">
              <label class="col-sm-2" for="logoUrl">logoUrl</label>
              <div class="col-sm-7">
                <input class="form-control" placeholder="logoUrl" formControlName="logoUrl">
                <span class="help-block" *ngIf="editForm.get('logoUrl').touched && editForm.get('logoUrl').hasError('required')">logoUrl is required</span>
              </div>
            </div>
            <div class="form-group" [ngClass]="{'has-error': editForm.get('abn').touched && editForm.get('abn').hasError('required')}">
              <label class="col-sm-2" for="abn">abn</label>
              <div class="col-sm-7">
                <input class="form-control" placeholder="abn" formControlName="abn">
                <span class="help-block" *ngIf="editForm.get('abn').touched && editForm.get('abn').hasError('required')">abn is required</span>
              </div>
            </div>
            <div class="form-group" [ngClass]="{'has-error': editForm.get('acn').touched && editForm.get('acn').hasError('required')}">
              <label class="col-sm-2" for="acn">acn</label>
              <div class="col-sm-7">
                <input class="form-control" placeholder="acn" formControlName="acn">
                <span class="help-block" *ngIf="editForm.get('acn').touched && editForm.get('acn').hasError('required')">acn is required</span>
              </div>
            </div>
        </form>
    </div>
</div>

Когда я запускаю код, я получаю сообщение об ошибке:

ОШИБКА TypeError: Невозможно прочитать свойство 'get' из неопределенного

и относится к компоненту chidlren html

<form [formGroup]="myForm" (ngSubmit)="save()" class="form-horizontal">

мои route.ts

{путь: 'organization / edit /: id', компонент: OrganizationEditComponent, разрешение: {organization: OrganizationResolver}},

Родительский компонент нормально получал данные организации из распознавателя. но дочерний компонент не может получить данные? что я должен делать ? и как отправить обратно данные "org" родителю? я должен использовать @ViewChild?

Edit: Я проверяю org в html дочернего компонента, набирая

{{ org | json }} 

это работает, но если я поставлю форму, как в коде выше, это не сработает. Кажется, у меня есть ошибка от детей "createform ()", где он не может получить данные org от родителя в OnInit

1 Ответ

0 голосов
/ 02 мая 2018

Я думаю, что вы ошиблись с названием формы.

вы написали editForm вместо myForm .

например.

'has-error': editForm.get('organizationName').touched
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...