简体   繁体   中英

Access child ngIf from parent component in Angular

I have a parent component and a child component. There is a ngif statement into child component. I want to use the same ngif into the parent component. Below is the sample code.

Child component:

`selector: 'child-component',
  template: `
    <div class="container">
      <div class="panel panel-danger">
        <div 
          class="panel-heading" 
          (click)="opened = !opened">
          Click me
        </div>
        <div 
          class="panel-body" 
          *ngIf="opened">body</div>
      </div>
    </div>
  `,
  styleUrls: [ './app.component.css' ]
})
export class ChildComponent  {
  opened = false;
  title = 'Hello Panel';
  body = 'this is the content';
}
`
parent component:
     <h3 *ngIf="loadcondition">This is Prent component</h3>

I tried to achieve the same with @Viewchild. In parent.component.ts--

import {ChildComponent} from './child-component';

   loadcondition : boolean = true;
    @ViewChild(ChildComponent) private childreference: ChildComponent; 

   ngAfterViewInit() {
       this.loadcondition = this.childreference.opened= false;
       console.log('on after view init', this.childreference);
     }

parent.component.html--

<div class="center"><h3 *ngIf="loadcondition">This is Parent component</h3> 
<child-component></child-component>
</div>

But unfortunately, childreference return undefined in the console. Is there any another way to access child conditions into parent component instead of @Viewchild.

if you use a reference variable, you can access to all the properties of children.

<div class="center">
  <h3 *ngIf="mychild.opened">This is Parent component</h3> 
  <child-component #mychild></child-component>
</div>

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