0

У меня есть три компонента: GalleryAddComponent, чтобы добавлять новый элемент, GalleryItemComponent, для редактирования элемента, FieldsComponent форма, которую я хочу использовать для валидации в компонентах: GalleryAddComponent и GalleryItemComponent. Все компоненты находятся в отцовском GalleryComponent.Когда я перехожу к компоненту GalleryAddComponent, чтобы добавить новый элемент, я получаю ошибку: ERROR TypeError: Cannot read property 'controls' of undefined . Та же ошибка и в компоненте: GalleryItemComponent.

Помогите решить эту проблему, чтобы логика редактирования и добавления работала правильно.

template GalleryAddComponent

<div class="card">
    <div class="card-body">
        <form [formGroup]="angForm" novalidate>
                <app-fields [formGroup]="angForm"></app-fields>
            <div class="form-group but-group">
                <button (click)="addPost(title.value, url.value);  angForm.reset(title.value, url.value)"
                        [disabled]="angForm.pristine || angForm.invalid"
                        class="btn btn-primary">Add
                </button>
                <a routerLink="/" class="btn btn-danger">Back</a>
            </div>
        </form>
    </div>
</div>

code GalleryAddComponent

export class GalleryAddComponent implements OnInit {
    angForm: FormGroup;
    isAdded: boolean = false;
    constructor(private fb: FormBuilder, private galleryService: GalleryService) {}

    ngOnInit() {
        this.angForm = this.fb.group({
            title: ['', Validators.required],
            url: ['', Validators.required]
        });
    }

    addPost(title: string, url: string): void {
        this.galleryService.add(title, url).subscribe(res => {
            this.isAdded = true;
        });
    }
}

template GalleryItemComponent

 <div class="card" *ngIf="toggleEdit">
        <h4>Edit your post</h4>
        <div class="card-body">
            <form [formGroup]="angForm" novalidate>
                <app-fields [formGroup]="angForm"></app-fields>
                <div class="form-group but-group">
                    <input type="button"
                           (click)="updatePost(title.value, url.value)"
                           [disabled]=" angForm.invalid"
                           class="btn btn-primary" value="Update Post">
                </div>
            </form>
        </div>
    </div>

template FieldsComponent

<div [formGroup]="formGroup">
    <div class="form-group">
        <label class="col-md-4">Picture Title</label>
        <input type="text" class="form-control" formControlName="title" minlength="1" #title/>
    </div>
    <div *ngIf="angForm.controls['title'].invalid && (angForm.controls['title'].dirty || angForm.controls['title'].touched)"
         class="alert alert-danger">
        <div *ngIf="angForm.controls['title'].errors.required">
            Title is required.
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-4">Picture Address (url)</label>
        <input type="url" class="form-control" formControlName="url" #url pattern="https?://.+"
               title="Include http://"/>
    </div>
    <div *ngIf="angForm.controls['url'].invalid && (angForm.controls['url'].dirty || angForm.controls['url'].touched)"
         class="alert alert-danger">
        Address(url) is required.
        <div *ngIf="angForm.controls['url'].errors.required ">

        </div>
    </div>
</div>

code FieldsComponent

export class FieldsComponent implements OnInit {
@Input() formGroup: FormGroup;

  constructor() {}

  ngOnInit() {}

}

1 ответ 1

-1

1) пробовал изменить название formGroup? 2) попробуй заменить angForm.controls['url'].invalid на angForm?.controls['url'].invalid и аналогично для всех. Скорее всего может быть проблема при первом рендере так как пытается взять property of undefined (форма еще не построилась) 3) раз уже используешь реактивные формы - лучше валидируй тоже реативно через Validators например: `

this.resetPasswordForm = this.formBuilder.group({
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required],
    }

`

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.