组件负载的角度变化变量

时间:2017-05-12 13:36:27

标签: angular

我有这个ruote配置:

const routes: Routes = [
    { path: 'score', component: ScoreComponent }
];

加载组件分数时,我想更改父组件中变量的值。

变量标题位于父组件模板中:

<div class="wrapper">
    <app-header></app-header>
    <app-menu [variablesForMenu]='variablesForMenu'></app-menu>
    <div class="content-wrapper">
        <section class="content-header">            
            <h1>
                {{title}}
            </h1>
        </section>
        <section class="content">
            <router-outlet></router-outlet>
        </section>
    </div>
</div>

我该怎么办?

我想使用EventEmitter,但我不知道如何

1 个答案:

答案 0 :(得分:3)

三种方法:

  1. 使用BehaviorSubject,在父级中订阅它,并在init中调用child中的next
  2. SomeService.service.ts

    em: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
    

    Parent.component.ts

    variableToChange: any;
    sub: Subscription;
    
    constructor(someService: SomeService){}
    
    ngOnInit() {
      sub.add(this.someService.em.subscribe(value => this.variableToChange = whatever));
    }
    

    Child.component.ts

    constructor(someService: SomeService){}
    
    ngOnInit() {
      this.someService.em.next(true);
    }
    
    1. 将变量从父项传递给子项作为输入,然后在init中的子项中更改该变量。
    2. Parent.component.ts

      variableToChange: any;
      

      Parent.component.html

      <child [variable]="variableToChange"></child>
      

      Child.component.ts

      @Input() variable: any;
      
      ngOnInit() {
        this.variable = 'whatever';
      }
      
      1. 使用EventEmitter
      2. Child.component.ts

        @Output() em: EventEmitter<any> = new EventEmitter();
        
        ngOnInit() {
          this.em.emit('something');
        }
        

        Parent.component.html

         <child (em)="setVariable($event)"></child>
        

        Parent.component.ts

         variableToChange: any;
        
         setVariable(event) {
          this.variable = event; // event is emitted value
         }