我是angular2的新手,不是专业人士。我有一个父子组件,当用户单击按钮时,子组件的选择器显示一些内容。因此,它应该是有条件的,也可以从子组件中使用。这是我的代码:
父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>


和父级组件:

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);
 }
}


现在我的问题是,当用户单击时,在父项中显示子项选择器的最简单方法是什么?因为错误是:无法读取未定义的属性'emkan'。我知道是因为* ngIf,但不知道该怎么办。
我也应该说我可以使用代码中的viewchild方法。
谢谢您的轻松帮助。

最佳答案

您的问题稍大一些,但我遇到了同样的问题,也许我可以帮我回答这个问题。

* ngIf从DOM中删除了HTML元素,因此ViewChild在DOM中找不到该Element。

首先,我想使用ngShow指令。但是在Angular 5中它不再存在。但是在版本5中,您可以轻松绑定到[hidden]属性,这不会从DOM中删除元素而是将其隐藏,例如ngShow指令和ViewChild可以再次找到该元素。

10-06 11:34