skip to Main Content

i want the first button to be clicked right when the page loads im building it using html,css, typescript

<div class="media-column">
 <!-- posts button -->
    <button #postsButton class="media-button"(click)="applyFilter('posts')">
      <span class="media-label">Posts</span>
    </button>
  <!-- images button -->
    <button class="media-button"(click)="applyFilter('images')">
      <span class="media-label">Pictures</span>
    </button>
 <!-- videos button -->
  <button class="media-button" (click)="applyFilter('videos')">
      <span class="media-label">Videos</span>
    </button>
  </div>

i tried but it didnt work, i didnt getthe button clicked

 @ViewChild('postsButton', { static: true }) postsButton!: ElementRef;

ngOnInit() {   
      this.postsButton.nativeElement.click();
  }

2

Answers


  1. When ngOnInit() is called, the template is not rendered yet. You need to use ngAfterViewInit() instead.

    @ViewChild('postsButton', { static: true }) postsButton!: ElementRef;
    
    ngAfterViewInit() {   
      this.postsButton.nativeElement.click();
    }
    

    For more information about the component lifecycle, check the docs.

    Login or Signup to reply.
  2. You should simply call the button click function applyFilter, without clicking it programatically, it does the same thing.

    ngOnInit() {   
        this.applyFilter('posts');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search