okarlsson
okarlsson

Reputation: 286

Access parent variable from child component template

I have two classes, Secure and Client. My Secure class is a parent of Client.

The idea is that when a class extends Secure, the constructor checks authentication and redirects to a login page if the user is not authenticated. The class looks like this:

export class Secure {

    protected user: User;

    constructor(public router: Router, public userHandler: UserHandler) {
        userHandler.checkAuthentication(this);
    }

    isLoggedIn(message: string, isLoggedIn: boolean) {
        if(!isLoggedIn){
            this.router.navigate(['/']);
        }
    }

    getUser(): User{
        return this.user;
    }
}

And my child-class looks like this:

export class ClientsComponent extends Secure{

  client: Client = new Client();

  clients: Array<Client>;

  constructor(public router: Router, public userHandler: UserHandler, public clientService: ClientService) {
      super(router, userHandler);

  }

  ngOnInit() {
    this.clientService.getAllUsers(this);
  }

  doRegister(){
      this.clientService.createNewClient(this.client.email, this);
  }

  callbackRegisterComplete(){
    this.clientService.getAllUsers(this);
  }

  callbackWithClients(clients:Array<Client>){
    this.clients = clients;
  }

}

In my Clients template I would like to check if the user in my Secureclass got a certain role:

<tr *ngFor="let client of clients; let i = index">
    <th scope="row">{{i+1}}</th>
    <td>{{client.email}}</td>
    <td>{{client.userStatus}}</td>
    <td *ngIf="user.isAdmin">...</td>
</tr>

But this produces the following error: Cannot read property 'isAdmin' of undefined

So my question is: Is there any way to access a variable in a parent class from the child class template? If not, is there any good ways to work around this?

Upvotes: 3

Views: 5214

Answers (2)

Rustam Goygov
Rustam Goygov

Reputation: 81

If your child component is strictly related only to its parent then you can use inheritance.

Just extend from parent and you'll have everything that parent has in your child component.

@Component({
  selector: 'task',
  template: `<task-body></task-body>`,
})
export class TaskComponent{
   taskType:any;
}

@Component({
  selector: 'task-body',
  template: `Here you can see variable from parent {{taskType}}`,
})
export class TaskBodyComponent extends TaskComponent{
   //also you can use parent variable in your child component as that 
    variable would exist on your child
   logSomething(){
      console.log(this.taskType);
   }
}

Upvotes: 2

Chrillewoodz
Chrillewoodz

Reputation: 28318

Instead of extending, simply use @Input() to pass data from a parent component to a child component:

parent template:

<child [someData]="data"></child>

This is the most efficient way to share data across components.

Now in child you can grab the data via this.someData or someData if you want it from the template.

Upvotes: 4

Related Questions