I have a usecase where I want to highlight the previously selected channel type(SMS or VOICE) option by user to recieve the OTP. I have already tried implementing ngAfterViewInit() like below.
############# Angular Component ####################
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>
What changes should I include to make sure that the CSS class gets added to the selected phoneType button after/once the page is rendered? I was of an impression that using ngAfterViewInit would solve the problem but document.getElementById() returns null even when the method is called from ngAfterViewInint?
2
Answers
ngAfterViewInit
runs after the components view is fully loaded, not after all the views are fully loaded, unlikewindow.onload
.You should use
[ngClass]
which can be used to add classes conditionally. Also prefer angular directives instead ofJS
orJQuery
, do go through angular.dev for reference.