W
W
webivan12016-01-11 21:18:45
Angular
webivan1, 2016-01-11 21:18:45

How to inherit attributes in Angular2?

Hello!
There is a parent component {App}, in which there is a request to the server to get information about the user, whether he is authorized or not, the response is written to {App.guest}:

import {Component} from 'angular2/core';
import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';
import {FORM_PROVIDERS} from 'angular2/common';

import {Core} from './service/Core';

import {Home} from './home/home';
import {About} from './component/About';
import {Contacts} from './component/Contacts';

@RouteConfig([
  { 
    path: '/', 
    component: Home, 
    name: 'Index' 
  },
  {
    path: '/about',
    component: About,
    name: 'About'
  },
  {
    path: '/contacts',
    component: Contacts, 
    name: 'Contacts'
  },
  { 
    path: '/**', 
    redirectTo: ['Index'] 
  }
])

@Component({
  selector: 'app',
  providers: [ ...FORM_PROVIDERS, Core ],
  directives: [ ...ROUTER_DIRECTIVES ],
  template: require('./template/layout.html')
})

export class App {
  public guest = true;

  constructor(public serviceCore: Core) {
    // Делаем запрос и записываем ответ в this.guest
  }

  login(login) {
    return this.guest = login;
  }
}

We are on the '/contacts' page, the Contacts component is working, it is not possible to get data from the parent App component, specifically the guest property.
import {Component} from 'angular2/core';

@Component({
  selector: 'contacts',
  template: require('../template/contacts.html'),
})

export class Contacts {
  public title: string;

  constructor() {
    this.title = 'Контакты';
                // Как вызвать this.guest из App
  }
}

At the same time, you need to make sure that when changing the properties of App.guest, it automatically changes in child components.
Help with component inheritance.
Tried via @Injectable(), inherits as a service, but when changing in the parent, the child does not redraw.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
thebarada, 2016-01-30
@thebarada

you need to specify a variable in the attribute of the nested component
+ declare the property in the class with the annotation @Input
https://egghead.io/lessons/angular-2-passing-data-...

X
Xandrio, 2017-05-19
@Xandrio

Nenene, you have broken logic, I do not advise.
Create an app-state (or user-state) service, store the necessary variables in it. Why do you need all this? The app component serves slightly different purposes.
and yes, use @Input.
But then again, you're not going to transfer a variable from an ancestor to an ancestor of a child to a child all the time, are you?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question