简体   繁体   中英

How to define a “global” variable in a component? (Angular4)

I have an app-editor-component which contains a lot of nested components inside it's structure. When the component is loaded, it creates an array: obj_list : MyObject[]

Many of the nested components will contain a <select> element, where one of the elements in obj_list has to be selected in each.

How is it possible to share this list with all the elements in the structure?

One way to share data between nested components is Input/Output+EventEmitter system.

Or, you can use shared service to transfer data between components. Here are some links to official docs and good post from firebase about component interaction:

Docs

Post

In your case, for example, you can pass obj_list from app-editor-component down to child components through Input s, then, in child components, observe <select> 's change event and emit changes back to app-editor-component .

But, if you have deep nesting, using service is better approach

The entity that is shared by several nesting components should be a service. This is naturally provided by Angular hierarchical injectors.

More importantly, if data is supposed to be changed asynchronously, components should be notified of this somehow. This is conveniently done with RxJS observables:

import { Subject } from 'rxjs/Subject';

@Injectable()
class Foo {
  objListSubject = new Subject();
  objList$ = this.objListSubject.asObservable();
}

@Component({
  providers: [Foo] // belongs to NgModule providers if the service is global
  ...
})
class ParentComponent {
  constructor(private foo: Foo) {
    ...
    this.foo.next(['bar']);
  }
}

@Component({
  template: `
    <select ...>
      <option *ngFor="foo.objList$ | async">
    </select>
  `,
  ...
});
class ChildComponent {
  constructor(public foo: Foo) {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM