Angular 5 Parent调用子组件

时间:2018-04-02 21:01:25

标签: angular components

我有一个使用primefaces / primeng库的树组件。当我点击树节点时,我希望孩子(帐户注册)加载给定节点的帐户。我无法让它正常工作。该帐户通过角度服务加载。

树组件:

import { Component, OnInit, Injectable, ViewChild } from '@angular/core';
import { Tree } from 'primeng/tree';
import{ TreeModule } from 'primeng/tree';
import { TreeNode } from 'primeng/api';
import { Router } from '@angular/router';
import { AccountRegisterComponent } from '../account-register/account-register.component';


@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html',
  styleUrls: ['./accounts.component.css']
})
@Injectable()
export class AccountsComponent implements OnInit {

@ViewChild(AccountRegisterComponent)
private accountRegister: AccountRegisterComponent;

  constructor(private router: Router) { }


  public nodes : TreeNode[];
  ngOnInit() {
    this.nodes =  [
      {     
          label: "Assets",
          data: "1",
          expandedIcon: "fa-folder-open",
          collapsedIcon: "fa-folder",
          selectable:true,
          children: [ 
            {
            label: "Asset1",
            data: "2",
            expandedIcon: "fa-folder-open",
            collapsedIcon: "fa-folder",
            selectable:true
          } 
        ]
      },
      {
        label: "Liabilities",
        data: "3",
        expandedIcon: "fa-folder-open",
        collapsedIcon: "fa-folder",
        selectable:true
    },
    {
      label: "Income",
      data: "4",
      expandedIcon: "fa-folder-open",
      collapsedIcon: "fa-folder",
      selectable:true
  },
  {
    label: "Expenses",
    data: "5",
    expandedIcon: "fa-folder-open",
    collapsedIcon: "fa-folder",
    selectable:true
},
    ];

  }

  nodeUnselect(event) {
    console.log("unselect " + event.node.label);
}

  nodeSelect(event) {
     this.router.navigateByUrl('/account/' + event.node.data);
     this.accountRegister.id = event.node.data;     
     console.log(event.node.label);
}
  expandAll(){
    this.nodes.forEach( node => {
        this.expandRecursive(node, true);
    } );
}

collapseAll(){
    this.nodes.forEach( node => {
        this.expandRecursive(node, false);
    } );
}

private expandRecursive(node:TreeNode, isExpand:boolean){
    node.expanded = isExpand;
    if(node.children){
        node.children.forEach( childNode => {
            this.expandRecursive(childNode, isExpand);
        } );
    }
  }
}

注册组件,该组件调用服务获取给定父帐户ID请求的数据:

import { Component, OnInit, Input, OnChanges, DoCheck } from '@angular/core';
import { NgSwitchCase } from '@angular/common';
import { ActivatedRoute} from '@angular/router';
import { Table } from 'primeng/table';
import { GuidGenService } from '../services/guid-gen.service';
import { SelectItem } from 'primeng/api';
import { Dropdown } from 'primeng/dropdown';
import { AccountsService } from '../services/accounts.service';

@Component({
  selector: 'app-account-register',
  templateUrl: './account-register.component.html',
  styleUrls: ['./account-register.component.css']
})
export class AccountRegisterComponent implements OnInit, OnChanges, DoCheck {

  @Input()
  public id : number;


  accounts : any[];

  cols: any[];

    dates: SelectItem[];

    colors: SelectItem[];

    selectedAccount: SelectItem[];
    targetAccounts: SelectItem[];

  constructor(private route: ActivatedRoute, private guidGen : GuidGenService, private accountServ : AccountsService) {
    this.route.params.subscribe( params => this.id = params.id );

    this.accounts =  accountServ.getAccounts(this.id);
    console.log("accounts is " + this.accounts.length)
  }

  public SetAccounts(id: number)
  {
    this.id=id;
    this.accounts = this.accountServ.getAccounts(this.id);
  }
  ngOnChanges()
  {
    console.log("ngOnChanges " + this.id.toString() );

  }

  AddClick()
  {

   var newId = this.guidGen.GetGuid();
    this.accounts.push(  { id: newId, date: 'New G' + newId, description: '51%', thisYearSale: '40%', lastYearProfit: '$54,406.00', thisYearProfit: '$43,342' })
  }
  DeleteClick(rowId){

    console.log("Delete " + rowId );
    var data = this.accounts.filter( val => val.id != rowId);
    this.accounts = data;

  }
  ngDoCheck() {

    //Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.
    //Add 'implements DoCheck' to the class.
    console.log("ngDoCheck() " + this.id.toString());

  //  this.accounts = this.accountServ.getAccounts(this.id);
  }
  ngOnInit() {
    console.log("ngInit");

    this.targetAccounts = [ 
      { label: "Cash", value:'cash'},
      { label: "Checking", value:'checking'},
      { label: "Investment", value:'investment'},
  ];
    this.cols = [
      { field: 'date', header: 'Date' },
      { field: 'description', header: 'Description' },
      { field: 'target', header: 'Target Account' },
      { field: 'amount', header: 'Amount' },
    ];

    var dt = new Date();
    dt.setUTCDate(Math.random() * 30);

    // if ( this.accounts == undefined )
    // {
    //   this.accounts = this.accountServ.getAccounts(this.id);
    // }
  }

}

服务:

        import { Injectable } from '@angular/core';

@Injectable()
export class AccountsService {

  constructor() { }

  accounts: any[];

  getAccounts(id:number) : any[]
  {


    var dt = new Date();
    this.accounts = [];
    this.accounts = [
      { id:"1", date: dt.toLocaleDateString(), description: 'Home Depot' + id.toString(), target: 'cash', amount: Math.random() * 1000.0},
      { id:"2", date: dt.toLocaleDateString(), description: 'Beer', target: 'checking', amount: Math.random() * 1000.0},
      { id:"3", date: dt.toLocaleDateString(), description: 'Salary', target: 'investment', amount: Math.random() * 1000.0},
      { id:"4", date: dt.toLocaleDateString(), description: 'AFAFA', target: '22%' , amount: Math.random() * 1000.0},
      { id:"5", date: dt.toLocaleDateString(), description: ' AGAG@$#@$@ ', target: '79%', amount: Math.random() * 1000.0},
      { id:"6", date: dt.toLocaleDateString(), description: 'ABCDEF ', target: ' 65%', amount: Math.random() * 1000.0},
      { id:"7", date: dt.toLocaleDateString(), description: 'Test me', target: '12%' , amount: Math.random() * 1000.0},
      { id:"8",  date: dt.toLocaleDateString(), description: '44%', target: '45%', amount: Math.random() * 1000.0}

    ];
    return this.accounts;
  }

}

1 个答案:

答案 0 :(得分:0)

事实证明我需要在订阅处理程序中调用该服务。

import { Component, OnInit, Input, OnChanges } from '@angular/core';
import { NgSwitchCase } from '@angular/common';
import { ActivatedRoute} from '@angular/router';
import { Table } from 'primeng/table';
import { GuidGenService } from '../services/guid-gen.service';
import { SelectItem } from 'primeng/api';
import { Dropdown } from 'primeng/dropdown';
import { AccountsService } from '../services/accounts.service';

@Component({
  selector: 'app-account-register',
  templateUrl: './account-register.component.html',
  styleUrls: ['./account-register.component.css']
})
export class AccountRegisterComponent implements OnInit, OnChanges {

    @Input()
    public accounts : any[];

    @Input()
    id : Number;

    cols: any[];

    selectedAccount: SelectItem[];
    targetAccounts: SelectItem[];

  constructor(private route: ActivatedRoute, private guidGen : GuidGenService, private accountServ : AccountsService) {

    // Need to call service inside of subscription callback.
    this.route.params.subscribe( params => { this.accounts = accountServ.getAccounts(params.id);this.id = params.id; });

    //this.accounts = accountServ.getAccounts( this.id);
    console.log("accounts is " + this.accounts.length)
  }

  ngOnChanges()
  {
    console.log("ngOnChanges");
  }

  AddClick()
  {

    var newId = this.guidGen.GetGuid();
    this.accounts.push(  { id: newId, date: 'New G' + newId, description: '51%', thisYearSale: '40%', lastYearProfit: '$54,406.00', thisYearProfit: '$43,342' })
  }
  DeleteClick(rowId){

    console.log("Delete " + rowId );
    var data = this.accounts.filter( val => val.id != rowId);
    this.accounts = data;

  }
  ngDoCheck() {

    //Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.
    //Add 'implements DoCheck' to the class.
    console.log("ngDoCheck()");

   // this.accounts = this.accountServ.getAccounts(this.id);
  }
  ngOnInit() {
    console.log("ngInit");

    this.targetAccounts = [ 
      { label: "Cash", value:'cash'},
      { label: "Checking", value:'checking'},
      { label: "Investment", value:'investment'},
  ];
    this.cols = [
      { field: 'date', header: 'Date' },
      { field: 'description', header: 'Description' },
      { field: 'target', header: 'Target Account' },
      { field: 'amount', header: 'Amount' },
    ];


  }

}

标记绑定到“帐户”并将更新树。

<p-table #dt [value]="accounts" [columns]="cols" selectiomMode="single"  scrollHeight="150px" [paginator]="true" [rows]="10" >