ngIf with viewchild

4.2k views Asked by At

I'm new at angular2 and not professional. I have a parent-child component that I want when user click on a button the selector of child component show something. So it should be condition and also it is used from a child component. Here are my codes: Parent Html:

<div *ngIf="page2">
      <add-property-page2></add-property-page2>
    </div>

    <div class="text-center col-sm-12">
      <button [disabled]="!propertyForm.form.valid"
              (click)="onSubmit($event,value,amlak)"
              type="submit" class="btn btn-success">Continue
      </button>
    </div>

and Parent component:

import {Component, OnInit, ViewChild, ViewEncapsulation, Input } from '@angular/core';
import {Amlak} from '../models/amlak';
import {AddPropertyPage2Component} from './add-paroperty-page2.component';
@Component({
 selector: 'add-property',
 styleUrls: ['./selection.css'],
 templateUrl: './add-property.html',
 providers: [DataService, Amlak],
 })
export class AddPropertyComponent  {
private page2: boolean;
@ViewChild(AddPropertyPage2Component)
private addPropertyPage2: AddPropertyPage2Component;
constructor(private amlak: Amlak, private dataService: DataService
) {
this.userLogined = AuthenticationService.check();
 }
onSubmit($event:any,value,amlak) {
$event.preventDefault();
if (this.page2) {
  this.amlak.emkanat = this.addPropertyPage2.emkan.filter(e => e.checked == 
 true);
 }
}

Now my question is this what is the easiest way to show selector of child in parent when user click. Because the error is : Cannot read property 'emkan' of undefined. I know it's because of *ngIf but don't know what should I do. Also I should say I can use the viewchild method like this is in the code. Thank you for your help in easy way.

1

There are 1 answers

0
parakoopa On

Your question is a little bit older but I had the same problem and maybe I can help others whith my answer.

*ngIf removes the HTML element from the DOM, so ViewChild can't find the Element in the DOM.

First I wanted to use the ngShow directive. But in Angular 5 it does not exist anymore. But in version 5 you can easily bind to the [hidden] property, this will not remove the element from the DOM but hide it, like the ngShow directive and ViewChild can finde the element again.