2

在 angular2 我有一个 addproperty 组件(祖父)和 addproperty2 组件(父)和一个复选框组件(子)。在祖父中有一个带有添加按钮的表单,如果用户单击父组件中的复选框,则会显示并再次添加按钮存在。祖父母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">Add
      </button>
    </div>

这意味着如果 page2 为真,它会在祖父母中显示父 html。祖父组件:

import {Component, OnInit, ViewChild, ViewEncapsulation,Input} from '@angular/core';
import {AddPropertyPage2Component} from "./add-paroperty-page2.component";
@Component({
selector: 'add-property',
templateUrl: './add-property.html'
})
export class AddPropertyComponent implements OnInit {
private page2: boolean;
@ViewChild(AddPropertyPage2Component)
private checkbox: AddPropertyPage2Component;
onSubmit($event: any) {
$event.preventDefault();
if(this.page2){
  this.amlak.emkanat = this.checkbox.emkan.filter(e=>e.checked == true);
 }
}

父 html:

<div class="col-md-12 form-group">
<checkbox></checkbox>
 </div>

父组件:

import {Component, OnInit,ViewChild} from '@angular/core';
import {CheckBoxComponent} from './checkbox.component';
@Component({
selector:'add-property-page2',
templateUrl:'./add-property-page2.html',
})
export class AddPropertyPage2Component{
 @ViewChild(CheckBoxComponent)
 private checkboxcomponent: CheckBoxComponent;
 public emkan = this.checkboxcomponent.emkanats;
  }

和复选框组件:

import {Component, OnInit} from '@angular/core';
import {checkBoxClass} from '../models/checkboxClass';
import {CheckBoxService} from '../services/checkbox.service';
@Component({
selector: 'checkbox',
styleUrls: ['./checkbox.css'],
templateUrl: './checkbox.html',
})
 export class CheckBoxComponent implements OnInit {
 public emkanats: checkBoxClass[];

 constructor(private checkboxService: CheckBoxService) {
  }

  ngOnInit() {
  this.checkboxService.getCheckboxes().subscribe(res => this.emkanats = 
  res);
  }
  }

这是复选框类:

export class checkBoxClass {
title:string;
 value:string;
checked:boolean;
 image:number;
 }

复选框服务:

import {Injectable} from '@angular/core';
import {checkBoxClass} from '../models/checkboxClass';
import {Http,Headers,Response} from '@angular/http';
 import { Observable }     from 'rxjs/Observable';
 import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable() export class CheckBoxService{
 private checkboxUrl:string = '../../checkbox.json';

 constructor(private http:Http){}

 getCheckboxes(): Observable<checkBoxClass[]> {
  return this.http.get(this.checkboxUrl)
  .map(response => response.json())
 }
 }

现在的错误是:无法读取未定义的属性“emkan”我在两个组件中使用了 viewchild 方法,但我不知道这个错误的原因。你能帮我用 viewchild 方法解决这个问题吗?非常感谢。

4

0 回答 0