“Viewchild Angular” Kode Jawaban

Nilai elemen input ViewChild Angular

// in html
<input #input type="text">
// in .ts
@ViewChild('input') input:ElementRef; 
//Output value
console.log(this.input.nativeElement.value);
Friendly Frog

Viewchild Angular

import { 
    Component, 
    OnInit, 
    ElementRef, 
    ViewChild, 
    OnDestroy, 
    ChangeDetectionStrategy, 
    ChangeDetectorRef } from '@angular/core';

import { Router } from '@angular/router';
import { User } from 'src/app/common/auth/user';
import { AuthService } from 'src/app/common/services/auth.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HeaderComponent implements OnInit, OnDestroy {
  @ViewChild('searchBar') searchBar: ElementRef | null = null;
  public signedIn: boolean = false;
  public authUser: User | null = null;
  private destroyNotifier$: Subject<boolean> = new Subject<boolean>();
  constructor(
    public authService: AuthService,
    private router: Router, 
    private snackBar: MatSnackBar, 
    private changeDetectorRef: ChangeDetectorRef) { }

  ngOnInit(): void {
    this.authService.authState
    .pipe(takeUntil(this.destroyNotifier$))
    .subscribe({
      next: (authState: AuthState) => {
        this.signedIn = authState.signedIn;
        this.authUser = authState.currentUser;
        this.changeDetectorRef.markForCheck();
      }
    });
  }
  ngOnDestroy(): void {
    this.destroyNotifier$.next(true);
    this.destroyNotifier$.complete();
  }
  logOut(): void {
    this.authService.logOut();
    this.router.navigateByUrl('/users/login');
  }
  findUsers(): void {
    const searchText = this.searchBar?.nativeElement.value;
    if(searchText == ''){
      this.snackBar.open('Enter a search text', 'Ok', {
        duration: 5 * 1000
      });
      return;
    }
    const result = this.authService.findUsers(searchText);
    console.log(result);
  }
}
EfficientCoder

Jawaban yang mirip dengan “Viewchild Angular”

Pertanyaan yang mirip dengan “Viewchild Angular”

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya