我有一个用例,我想突出显示用户之前选择的通道类型(短信或语音)选项以接收 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?
import { HostListener } from '@angular/core';
let contactMethod: string = 'sms';
@HostListener('window:load')
onLoad() {
this.highlightSelectedMethod(this.contactMethod);
}
与 ngAfterViewInit
不同,
window.onload
在组件视图完全加载后运行,而不是在所有视图完全加载后运行。