角度:解决订阅中的渲染

时间:2020-01-10 14:24:21

标签: angular typescript

当“ noRender”更改时,我想在DOM中进行一些更改。 'noRender'隐藏所有DOM,并在subscription方法中更改。我尝试使用“ onChanges”-没用。我决定在subscribe方法中编写代码,但是在subscribe方法完成后执行重新渲染。怎么解决呢?请帮忙

this.http.post(Main.BASE_URL + StaticData.SIGN_URL, {})
  .subscribe((value: Response) => {
    this.noRender = false;
    if(document.querySelector('.steps-list-line')){
        (document.querySelector('.steps-list-line') as HTMLElement).style.width =
        (document.querySelector('.active') as HTMLElement).offsetWidth +
        (document.querySelector('.active') as HTMLElement).offsetLeft + 'px';
    }
  } 
});

1 个答案:

答案 0 :(得分:1)

示例1

要检测noRender变量中值的变化,可以将此变量的类型更改为BehaviorSubject<boolean>。多亏了这一点,您才有机会订阅数据流。

export class SomeComponent{

    noRender = new BehaviorSubject<boolean>(false);

    constructor() {
        this.noRender.subscribe((newValue) => {
            // handle value changed
        });
    }

    someAction() {
        // change value of the noRender subject
        this.noRender.next(true);
    }

}

示例2

如果noRender变量是输入属性,则可以使用property-watch-decorator(链接:https://www.npmjs.com/package/property-watch-decorator),该变量允许检测输入属性的变化。

export class SomeComponent{

    @OnChange(function(this: SomeComponent, newValue: boolean){
        // handle value changed
    })
    @Input() noRender: boolean;

}