Angular 2 - обнаружение, когда свойство, связанное с недвижимостью, получает значение

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

Например

Это особенность компонента

import {
    Component,
    OnInit,
    Input,
    OnChanges,
    SimpleChanges
} from '@angular/core';
@Component({
    selector: 'feature-component',
    templateUrl: './template.html',
    styleUrls: ['./style.sass'] 
}) 
export class FeatureComponent implements OnInit, Onchanges {

    @Input() bondedProperty: any;

    ngOnInit() {

    }

    ngOnChanges(simpleChanges: SimpleChanges) {
        // not called inside the setInterval function
        console.log('the bonded property received any value.');
    }

}

Компонент приложения

import {
    Component,
    AfterViewInit
} from '@angular/core';
@Component({
    selector: 'app-component',
    templateUrl: './template.html',
    styleUrls: ['./style.sass'] 
}) 
export class AppComponent implements AfterViewInit {

    bondedProperty: any;

    constructor() {
        this.bondedProperty = 10;
    }

    ngAfterViewInit() {
        const
            interval = setInterval(
                () => {
                    this.bondedProperty = 10;
                    console.log('function called after interval');
                    clearInterval(interval);
                }, 5000
            );
    }

}

И, наконец, шаблон приложения

<feature-component
    [bondedProperty]="bondedProperty"
>
</feature-component>

Проблема в том, что если в bondedPropertyngOnChanges не называется, а ngDoCheck метод не решает мою проблему, потому что я не знаю, было ли "изменение" в bondedProperty,

2 ответа

Один простой способ это изменить bondedProperty переменная, чтобы быть объектом.

до:

this.bondedProperty = 10;

после:

this.bondedProperty = { 'value': 10 };

Таким образом, обнаружение изменений перехватит ваше событие обновления, если значение в нем будет таким же.

StackBlitz DEMO

Насколько я знаю, это не может быть достигнуто с ngOnChanges или же @Input setters как Angular предназначен только для вызова ngOnChanges или setter если значение действительно меняется.

Если вы хотите обнаружить новые значения, даже если они совпадают с предыдущим значением, то вам действительно нужно обнаружить какое-то событие. Вы могли бы использовать RxJS BehaviorSubject для такого рода целей.

FeatureComponent

import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';
import { BehaviorSubject }  from 'rxjs';
@Component({
    selector: 'feature-component',
    template: 'property: {{ bondedProperty$ | async }}',
    styleUrls: ['./style.sass'] 
}) 
export class FeatureComponent implements OnInit, Onchanges {

    @Input() bondedProperty$: BehaviorSubject<any>;

    ngOnInit() {
      this.bondedProperty$.subscribe(value => 
        console.log('the bonded property received any value.')
      );
    }

}

AppComponent

import { Component, AfterViewInit } from '@angular/core';
import { BehaviorSubject }  from 'rxjs';
@Component({
    selector: 'app-component',
    template: '<feature-component [bondedProperty$]="bondedProperty$"></feature-component>',
    styleUrls: ['./style.sass'] 
}) 
export class AppComponent implements AfterViewInit {

    bondedProperty$ = new BehaviorSubject<any>(0);

    constructor() {
        this.bondedProperty$.next(10);
    }

    ngAfterViewInit() {
        const
            interval = setInterval(
                () => {
                    this.bondedProperty$.next(10);
                    console.log('function called after interval');
                    clearInterval(interval);
                }, 5000
            );
    }

}

https://stackblitz.com/edit/angular-so-54059234-eshtnr

Другие вопросы по тегам