如何在angular2中更改子组件的父变量

时间:2017-11-20 15:26:03

标签: angular events

我的父组件html:

<app-calendar-component [view]="calView" [callback]="calendarOptions" ></app-calendar-component>
<app-weekdetails-component *ngIf="test"></app-weekdetails-component>

我的父组件ts:

public test:boolean=false;

appCalendarComponent:

ngOnInit(){
Calling services here and using data, after this process I need to set 
my variable test to be true which is defined in parent component.
}

因此,当初始化第一个子节点(appCalendarComponent)时,我需要将变量 test 设置为true。

1 个答案:

答案 0 :(得分:5)

您应该使用输出方式与父组件进行通信。

关于孩子:

import { Component, Output, EventEmitter } from '@angular/core';

@Output() componentInit = new EventEmitter<>();

ngOnInit(){
Calling services here and using data, after this process I need to set 
my variable test to be true which is defined in parent component.

//After init
 this.componentInit.emit();
}

在父母身上:

HTML:

<app-calendar-component 
                  (componentInit)="componentInitialize()" 
                  [view]="calView" 
                  [callback]="calendarOptions">
</app-calendar-component>

打字稿:

componentInitialize():void{
 this.test = true;
}
相关问题