ngOnChanges not firing when input property changed

前端 未结 4 521
陌清茗
陌清茗 2020-12-17 19:30

Can you programatically trigger angular\'s change detection when mutating a component property in angular2?

@Compon         


        
4条回答
  •  独厮守ぢ
    2020-12-17 20:34

    I was having the same issue, and this is a simple but not very elegant workaround I am using. Pass in another property to force trigger ngOnChanges method

    In the parent component class, whenever you want to manually fire the ngOnChanges method on child component, just modify "changeTrigger" property

    ParentComponent Class (poll-stat-chart is the child component)

         @Component({
            directives: [PollStatChartCmp],
            template: `
                
    ` } export class ParentComponent { changeTrigger = 1; barData = [{key:1, value:'1'}, {key:2, value'2'}]; triggerChild() { this.barData[0].value = 'changedValue'; //This will force fire ngOnChanges method of PollStatChartComponent this.changeTrigger ++ ; } }

    And then in child component class, add a property [changeTrigger]

        @Component({
            selector: '[poll-stat-chart]',
            inputs: ['barData', 'changeTrigger'],
            template: `
                

    This should be a BAR CHAR

    ` }) export class PollStatChartCmp { barData; changeTrigger; constructor(private elementRef: ElementRef) { this.render(); } ngOnChanges(changes) { console.log('ngOnChanges fired'); this.render(); } render() { console.log('render fired');} }

提交回复
热议问题