在 DOM 加载或视图渲染后运行函数的最佳方式是什么?

问题描述 投票:0回答:1

我有一个用例,我想突出显示用户之前选择的通道类型(短信或语音)选项以接收 OTP。我已经尝试过像下面这样实现 ngAfterViewInit() 。

############## 角度分量 ######################

let contactMethod: string = 'sms';  //Previously selected phonetype by user

ngAfterViewInit(): void {
  this.highlightSelectedMethod(this.contactMethod);

}

private highlightSelectedMethod(phoneType: string) {
  let selectedClass = 'selected';    //CSS class which highlights the selected phoneType
  let selectedPhoneType = document.getElementById(phoneType)   //When I log the selectedPhoneType, the value is turning out to be null which I think is becuase DOM is not loaded. 

if(selectedPhoneType){
  element.classlist.add(selectedClass);  //This if block is not running as selectedPhoneType is null when the code runs.
}

}

############ HTML ############

<button id='sms'>sms</button>

<button id='voice'>voice</button>

我应该进行哪些更改以确保在页面呈现之后/一旦将 CSS 类添加到所选的phoneType 按钮?我的印象是使用 ngAfterViewInit 可以解决问题,但即使从 ngAfterViewInint 调用该方法, document.getElementById() 也会返回 null?

javascript angular typescript user-interface frontend
1个回答
0
投票
import { HostListener } from '@angular/core';

let contactMethod: string = 'sms';
@HostListener('window:load')
onLoad() {
    this.highlightSelectedMethod(this.contactMethod);
}

ngAfterViewInit

 不同,
window.onload
在组件视图完全加载后运行,而不是在所有视图完全加载后运行。

© www.soinside.com 2019 - 2024. All rights reserved.