Как вручную изменить обнаружение (OnPush) несвязанного компонента (используя Observables)? - PullRequest
0 голосов
/ 18 марта 2019
  1. FormConfigComponent : модальный компонент
  2. FormContentsComponent : мой компонент, который необходимо обновить.

Я имеюкомпонент (FormContentsComponent), который отправляет некоторую информацию другому компоненту (FormConfigComponent).Они не связаны (parent -> child).

Компонент (FormContentsComponent) должен быть только обновлен, когда пользователь закрывает модальное (FormConfigComponent).

Как мне этого добиться?Нужно ли создавать службу, которая уведомляет об изменениях?

FormContentsComponent

import { Component, OnInit, Input, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { FormContentConfigService } from '../../services/form-content-config.service';

@Component({
    selector: 'app-form-contents',
    templateUrl: './form-contents.component.html',
    styleUrls: ['./form-contents.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class FormContentsComponent implements OnInit {
    @Input() column;

    sendDataToModal(content): void {
        this.formContentConfigService.setContent(content);
    }
}

FormConfigService

import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class FormContentConfigService {

    newFormConfigSubject = new Subject<any>();

    constructor() {}

    setContent(content) {
        this.newFormConfigSubject.next(content);
    }

    getContent() {
        return this.newFormConfigSubject.asObservable();
    }
}

FormConfigComponent

import { Component, OnInit, Input, Output, ViewChild, TemplateRef, EventEmitter, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { FormContentConfigService } from './../../services/form-content-config.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NgbModal, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { Observable } from 'rxjs';

@Component({
    selector: 'app-form-config',
    templateUrl: './form-config.component.html',
    styleUrls: ['./form-config.component.css'],
    //changeDetection: ChangeDetectionStrategy.OnPush
})
export class FormConfigComponent implements OnInit {
    @Input() formConfig: FormGroup;
    @ViewChild('modal') modal: TemplateRef<any>;

    closeResult: string;
    options: NgbModalOptions;

    constructor(
        private formContentConfig: FormContentConfigService,
        private fb: FormBuilder,
        private modalService: NgbModal,
        private cd: ChangeDetectorRef
    ) { }

    ngOnInit() {
        this.options = {
            size: 'lg',
            backdrop : 'static',
            keyboard : false,
            centered: true
        };
        this.formContentConfig.getContent().subscribe(
            (d) => {
                let data = {...d};

                this.formConfig = this.fb.group({
                    html: this.fb.group({                     
                        'text': [data.html.text, [
                           Validators.required
                        ]],
                    })
                });

                let m = this.modalService.open(this.modal, this.options)
                m.result.then((result) => {
                    this.closeResult = `Closed with: ${result}`;
                    if (typeof d.html !== undefined) {
                        d.html = {...d.html, ...this.formConfig.value.html};

                    }

                    console.log(d);

                }, (reason) => {
                    //this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
                });


            }
        );
    }


}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...