skip to Main Content

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


  1. import { HostListener } from '@angular/core';
    
    let contactMethod: string = 'sms';
    @HostListener('window:load')
    onLoad() {
        this.highlightSelectedMethod(this.contactMethod);
    }
    

    ngAfterViewInit runs after the components view is fully loaded, not after all the views are fully loaded, unlike window.onload.

    Login or Signup to reply.
  2. You should use [ngClass] which can be used to add classes conditionally. Also prefer angular directives instead of JS or JQuery, do go through angular.dev for reference.

    <button id='sms' [ngClass]="{'selected': contactMethod === 'sms'}">sms</button>
    
    <button id='voice' [ngClass]="{'selected': contactMethod === 'voice'}">voice</button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search