How can I read a component property from an other component with Angular 14

Viewed 23

I just want to read a string property from an other component. If I search I find solutions about *ngIf/ngFor, but in my case I don't show this property in html file. I just want to read the string property from an other component.

export class LoginComponent implements OnInit {

// THIS PROPERTY I WANT TO READ FROM AN OTHER COMPONENT
userRefid!: string;

  onSubmit(): void {
    const { email, password } = this.form;
    this.authService.login(email, password).subscribe({
      next: data => {
        this.storageService.saveUser(data);
        this.isLoginFailed = false;
        this.isLoggedIn = true;
        this.roles = this.storageService.getUser().roles;

        // HERE I GET THE VALUE FROM DB
        this.userRefid = this.storageService.getUser().refid; 
        this.reloadPage();
      },
      error: err => {
        this.errorMessage = err.error.message;
        this.isLoginFailed = true;
      }
    });
  }
}

export class ModeratorComponent implements OnInit, AfterViewInit {
  @ViewChildren(LoginComponent) loginComponent!: LoginComponent;
  currentUserRefid: any;


  ngAfterViewInit(): void {
    this.currentUserRefid = this.loginComponent.userRefid;
  }

}

In the function ngAfterViewInit the this.loginComponent gets always: ERROR TypeError: Cannot set properties of undefined (setting 'userRefid') the loginComponent is always undefined

I want to know what I have to use, ViewChild/ViewChildren or maybe something else to exchange properties from one component to an other.

1 Answers

Given the little piece of code you provided, it's probably because your component is not displayed.

Check that the LoginComponent is NOT in a tag that contains a *ngIf.

Or better, provide the HTML for the parent component !

Related